C++使用mutex对多thread进行变量保护

thread可以在C++中创建多线程调用函数,mutex可以对一些公共变量进行保护,代码如下:

代码

#include <iostream>
#include <thread>
#include <mutex>

std::mutex m;//you can use std::lock_guard if you want to be exception safe
int i = 0;

void makeACallFromPhoneBooth()
{
    m.lock();//man gets a hold of the phone booth door and locks it. The other men wait outside
    //man happily talks to his wife from now....
    std::cout << i << " Hello Wife" << std::endl;
    i++;//no other thread can access variable i until m.unlock() is called
    //...until now, with no interruption from other men
    m.unlock();//man lets go of the door handle and unlocks the door
}

int main()
{
    //This is the main crowd of people uninterested in making a phone call

    //man1 leaves the crowd to go to the phone booth
    std::thread man1(makeACallFromPhoneBooth);
    //Although man2 appears to start second, there's a good chance he might
    //reach the phone booth before man1
    std::thread man2(makeACallFromPhoneBooth);
    //And hey, man3 also joined the race to the booth
    std::thread man3(makeACallFromPhoneBooth);

    man1.join();//man1 finished his phone call and joins the crowd
    man2.join();//man2 finished his phone call and joins the crowd
    man3.join();//man3 finished his phone call and joins the crowd
    return 0;
}

结果

  1. 以上代码运行结果如下:
0 Hello Wife
1 Hello Wife
2 Hello Wife
  • mutex对公共变量 i i i进行了保护,mutex加锁后,其他线程无法访问变量 i i i
  1. 注释掉第10行和第15行后,运行结果如下:
000 Hello Wife Hello Wife Hello Wife
  • 没有了mutex的保护,任何线程都可以访问变量 i i i,故所有输出的 i i i的值都是0。

其他写法

其中makeACallFromPhoneBooth函数还可以写成以下形式:

void makeACallFromPhoneBooth()
{
    //man gets a hold of the phone booth door and locks it. The other men wait outside,
    // man lets go of the door handle and unlocks the door
    std::lock_guard<std::mutex> locker(m);
    //man happily talks to his wife from now....
    std::cout << i << " Hello Wife" << std::endl;
    i++;//no other thread can access variable i until m.unlock() is called
    //...until now, with no interruption from other men
}

通过std::lock_guard<std::mutex>也可以进行变量的保护。

猜你喜欢

转载自blog.csdn.net/linghu8812/article/details/108517177