c++多线程并发 基础入门 --互斥量mutex, 原子变量atomic

c++多线程并发 基础入门 --互斥量mutex, 原子变量atomic,第1张

1. 没有mutex

#include 
#include 
#include 

int globalVariable = 0;

void task1()
{
    for(int i = 0; i < 1000000; i++)
 	{
        globalVariable++;
        globalVariable--;
    }
}

int main(int argc, const char * argv[]) 
{
    std::thread t1(task1);
    std::thread t2(task1);
    
    t1.join();
    t2.join();
    
    std::cout<<"current value is "<<globalVariable<<std::endl;
}

xcode, command+r 运行结果为1,本来++和-- ,最后结果为0才对的,但是最后结果为1。
current value is 1
Program ended with exit code: 0

2. 加上mutex

#include 
#include 
#include 

std::mutex mtx;
int globalVariable = 0;

void task1()
{
    for(int i = 0; i < 1000000; i++)
    {
        mtx.lock();
        globalVariable++;
        globalVariable--;
        mtx.unlock();
    }
}

int main(int argc, const char * argv[]) {

    std::thread t1(task1);
    std::thread t2(task1);
    
    t1.join();
    t2.join();
    
    std::cout<<"current value is "<<globalVariable<<std::endl;
}

macOS xcode, command+r 运行结果为0, 正确。
current value is 1

锁之间的代码(上锁和解锁之间的代码段)叫做临界区代码段:
globalVariable++;
globalVariable–;

3. 死锁
目前这里很简单,只有两行,实际情况可能复杂:
临界区代码段:

mtx.lock();
globalVariable++;
globalVariable--;
//callAFUNC(); throw

//if(1==1)
//{
//return;
//}
mtx.unlock();

情况一:
callAFUNC(); throw
调用函数后抛出异常,后面没有解锁

情况二:
if(1==1)
{
return;
}
有return, 直接返回,也没有解锁

情况三:

#include 
#include 
#include 

std::mutex mtx1;
std::mutex mtx2;
int globalVariable = 0;

void task1()
{
    for(int i = 0; i < 1000000; i++)
    {
        mtx1.lock();
        mtx2.lock();
        globalVariable++;
        globalVariable--;
        
        mtx1.unlock();
        mtx2.unlock();
    }
}

void task2()
{
    for(int i = 0; i < 1000000; i++)
    {
        mtx2.lock();
        mtx1.lock();
        globalVariable++;
        globalVariable--;
        
        mtx2.unlock();
        mtx1.unlock();
    }
}

int main(int argc, const char * argv[]) 
{
    std::thread t1(task1);
    std::thread t2(task2);
    
    t1.join();
    t2.join();
    
    std::cout<<"current value is "<<globalVariable<<std::endl;
}

task1中先对mtx1 上锁,task2中先对mtx2上锁,然后task1中再想对mtx2上锁,task2中对mtx1上锁,这样会产生矛盾,陷入矛盾,下面的代码不能执行,上锁顺序不同产生死锁。

对于情况一 情况二,程序中途满足某些提条件退出,没来得及解锁情况,可以用程序标准库中提供的std::lock_guardstd::mutex lock(mtx1) 来管理互斥量,

std::lock_guard<std::mutex> lock(mtx1)
std::lock_guard<std::mutex> lock(mtx2)

lock_guard类 即对象创建的时候加锁,析构的时候会解锁,程序不需要再写 .lock() 和 .unlock() 这些了。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1323553.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-12
下一篇2022-06-12

发表评论

登录后才能评论

评论列表(0条)

    保存