C++线程基础——创建多个线程以及互斥量使用

2019-04-29  本文已影响0人  侠之大者_7d3f

引言

本文主要内容:


开发测试环境


创建多个线程

一般需要创建多个线程的时候,可以采用std::vector + std::thread 的方式,如下所示:

代码

#include<iostream>
#include<vector>
#include<thread>

using namespace std;

void func1(int a) {
    printf("a=%d\t 线程id=%d\n", a, std::this_thread::get_id());
}

int main() {

    /*
    创建多个线程
    */

    vector<thread> my_threads;

    for (int i = 0; i < 10; i++)
    {
        my_threads.push_back(thread(func1, i));
    }

    for (auto& i:my_threads)
    {
        i.join();
    }


    /*for (auto iter=my_threads.begin();iter!=my_threads.end();++iter)
    {
        iter->join();
    }*/


}
image.png

每个线程的id都不同,说明确实创建了10个线程。


多线程访问共享数据

共享数据按照操作类型可分为:

多线程访问只读数据

#include<iostream>
#include<vector>
#include<thread>

using namespace std;

// 共享数据
vector<int> my_data{ 1, 2, 3, 4, 5 };

//这里必须是const类型修饰
void readData( const std::vector<int>& d) {

    cout << d[0] << d[1] << d[2] << d[3] << d[4] << " 线程id=" << std::this_thread::get_id() << endl;
}


int main() {
  
        //创建2个线程
    thread read_thread1(readData, my_data);
    thread read_thread2(readData, my_data);
    
    read_thread1.join();
    read_thread2.join();

}
image.png

虽然运行结果打印是乱的,但是读取的数据仍然是12345, 没有发生错误。

结论:
如果共享数据是只读的话,则多线程读取是安全稳定的,不需要特殊手段,直接读取即可。


多线程操作有读有写数据

#include<iostream>
#include<vector>
#include<thread>

using namespace std;

//共享数据
int num_ticket = 20;

void sell() {
    
    while (true)
    {
        if (num_ticket > 0)
        {
                      //共享数据写操作
            num_ticket -= 1;
            printf("订票成功,当前余票数=%d,线程id=%d\n", num_ticket, std::this_thread::get_id());
        }
        else
        {
            printf("票已售完!,线程id=%d\n", std::this_thread::get_id());
            return;
        }
    }
    

}

int main() {

    thread my_thread1(sell);
    thread my_thread2(sell);

    my_thread1.join();
    my_thread2.join();



}
image.png

两个线程进行订票服务,刚开始线程id=12624的先运行,成功订票2张;之后CPU进行了上下文切换,线程id=7096的线程开始运行,成功订票7张,余票为10张; 此时CPU又进行上下文切换,线程id=12624查询到余票还有16张,显然错误;.....
说明,在多线程中,对共享数据进行有读有写操作会存在数据一致性问题

解决思路
多线程操作有读有写的共享数据,读和写不要同时进行,读的时候不能写,写的时候不能读


引入互斥量

在C++中,为了解决多线程保护共享数据问题,引入了互斥量

类似于生活中的问题,比如厕所的坑是公共资源,张三、李四是两个线程,都可能随时去上厕所,而且可能同一时刻一起去, 因此为了避免2人抢坑打起来,厕所的每个坑有门以及锁, 如果张三首先占坑了,为了不影响自己上厕所,此时将门锁住(加锁),这样李四只能在门外等; 当张三用完了,此时打开锁子(解锁),李四进去之后也进行加锁,防止其他人进入,之后用完有解锁。

C++多线程中
互斥量: 互斥量是一个类对象,可以理解为一把,具有2种行为"加锁"和"解锁"。多个线程尝试使用lock()成员函数进行加锁,只有一个线程能够锁定成功(成功的标志是lock()函数返回了return),如果没有加锁成功,那么流程一直卡在lock()这里不断尝试加锁。

简单的讲,互斥量就是使得2个线程不能同时操作共享数据,这就是互斥的含义。

在C++中,引入信号量,需要包含头文件
#include<mutex>
创建一个互斥量对象
std::mutex my_mutex;

互斥量的方法/成员函数:

#include<iostream>
#include<vector>
#include<list>
#include<thread>
#include<mutex>

using namespace std;


int num_ticket = 200;

void sell() {

    while (true)
    {
        if (num_ticket > 0)
        {
            num_ticket -= 1;
            printf("订票成功,当前余票数=%d,线程id=%d\n", num_ticket, std::this_thread::get_id());
            std::this_thread::sleep_for(chrono::microseconds(200));
        }
        else
        {
            printf("票已售完!,线程id=%d\n", std::this_thread::get_id());
            return;
        }
    }
    


}






int main() {

    std::vector<thread> my_threads;
    for (int i = 0; i < 10; i++)
    {
        my_threads.push_back(thread(sell));
    }

    for (auto& i:my_threads)
    {
        i.join();
    }



}

image.png

在代码中加入互斥量
my_mutex.lock() 加锁
my_mutex.unlock() 解锁


#include<iostream>
#include<vector>
#include<list>
#include<thread>
#include<mutex>

using namespace std;


int num_ticket = 200;
mutex my_mutex;

void sell() {

    while (true)
    {
        my_mutex.lock();
        if (num_ticket > 0)
        {
            num_ticket -= 1;
            printf("订票成功,当前余票数=%d,线程id=%d\n", num_ticket, std::this_thread::get_id());
            my_mutex.unlock();
            std::this_thread::sleep_for(chrono::microseconds(200));
        }
        else
        {
            printf("票已售完!,线程id=%d\n", std::this_thread::get_id());
            return;
        }
    }
    


}






int main() {

    std::vector<thread> my_threads;
    for (int i = 0; i < 10; i++)
    {
        my_threads.push_back(thread(sell));
    }

    for (auto& i:my_threads)
    {
        i.join();
    }



}
image.png
image.png

std::lock_guard()

互斥量用法总结

互斥量std::mutex是一个类对象,具有lock()unlock()2个成员方法,lock()是加锁, unlock()是解锁。

引入std::lock_guard()

由于使用std::mutex()需要进行lock()以及unlock(), 但是在实际开发中由于各种原因,往往会忘记unlock(),这样会导致锁死。C++中为了解决这情况,引入了一个类模板 std::lock_guard(), lock_guard()字面意思保证lock

注意:使用lock_guard()之后就不需要使用mutex::lock(),mutex::unlcok()

std::mutex my_mutex;
std::lock_guard<std::mutex> mylock_guard(my_mutex);

例子

#include<iostream>
#include<vector>
#include<list>
#include<thread>
#include<mutex>

using namespace std;


int num_ticket = 200;
mutex my_mutex;

void sell() {

    while (true)
    {
        //my_mutex.lock();
        std::lock_guard<std::mutex> mylock_guard(my_mutex);
        if (num_ticket > 0)
        {
            num_ticket -= 1;
            printf("订票成功,当前余票数=%d,线程id=%d\n", num_ticket, std::this_thread::get_id());
            //my_mutex.unlock();
            std::this_thread::sleep_for(chrono::microseconds(200));
        }
        else
        {
            printf("票已售完!,线程id=%d\n", std::this_thread::get_id());
            return;
        }
    }



}



int main() {

    std::vector<thread> my_threads;
    for (int i = 0; i < 10; i++)
    {
        my_threads.push_back(thread(sell));
    }

    for (auto& i : my_threads)
    {
        i.join();
    }

}


线程死锁问题

什么是死锁?
死锁字面理解就是锁死了,线程卡死了。
C++中死锁:产生死锁的前提,线程中必须至少包含2及以上的互斥量。

举例
张三在北京的火车站等李四,李四在西安的火车站等张三,两人等一辈子也见不着面

C++线程中中死锁的例子
假设有2个线程A, B, 以及2个锁(互斥量)金锁(JinLock)、银锁(YinLock)
(1) 线程A执行过程中,A线程抢到了金锁,将金锁成功lock(),之后线程A的流程是抢占获取银锁,但是此时CPU进行了上下文切换...
(2) 上下文切换之后,B线程开始执行,B线程去抢占银锁,由于银锁没有被锁,因此B线程抢占银锁成功,并且将银锁lock()成功,之后B线程去抢占金锁。 这种情况下,就产生了死锁
(3) 线程A因为拿不到银锁,流程走不下去(后面的代码有解锁金锁的,但是无法执行,金锁无法打开)
(4) 线程B因为拿不到金锁,流程走不下去(后面的代码有解锁银锁的,但是无法执行,银锁无法打开)

image.png

死锁的一般解决方案
保证2个互斥量上锁顺序一致


std::lock()函数模板

用于多个互斥量


总结

本文简单介绍了多个线程的创建方式,以及多线程访问共享数据存在的问题,最后介绍了互斥量概念, 关于互斥量的使用下文继续探讨。

上一篇 下一篇

猜你喜欢

热点阅读