目录
C++11线程间同步方式_c++11线程同步_东东儿的博客-CSDN博客
一、背景
当有两个线程,同时对一个变量进行修改,此时变量没有按时序被修改,就导致两个线程的修改出现叠加,使得最终结果不符合预期,如下:
#include <iostream>
#include <thread>
using namespace std;
int a = 0;
void fun() {
for (int i = 0; i < 10000000; i++) a++; //当数字较小时(<100000)结果正常,但是较大时就有问题
}
int main()
{
thread ta(fun);
thread tb(fun);
ta.join();
tb.join();
cout << a << endl; //预期20000000
return 0;
}
为解决以上问题,需要在两个线程同时修改同一个变量时,让其中一个先改,另一个等候。
二、方法
1.互斥锁
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex m;
int a = 0;
void fun() {
for (int i = 0; i < 10000000; i++){ //当数字较小时(<100000)结果正常,但是较大时就有问题
m.lock();
a++;
m.unlock();
}
}
int main()
{
thread ta(fun);
thread tb(fun);
ta.join();
tb.join();
cout << a << endl; //预期20000000
return 0;
}
2.自旋锁
3.条件变量
就是condition_variable,例如有两个线程,其中一个线程A达到某条件时,A暂停执行,另一个线程B接着执行,一旦A满足条件则继续执行。
应用场景:
生产者消费者模型,生产数据多了暂停等待,消费数据没有了暂停等待。