C++多线程编程第十三讲--补充知识
//(1)补充一些知识点
//(1.1)虚假唤醒
// wait(), notify_one(), notify_all() 使用非常频繁的接口
// 虚假唤醒是指没有满足条件的时候被唤醒了。
//(1.2)atomic
#include<iostream>
#include<thread>
#include<vector>
#include<list>
#include<mutex>
using namespace std;
class A
{
public:
atomic<int> ato;
A()
{
ato = 0;
//std::atomic<int> ato2 = ato; //这种赋值操作是不被允许的
//std::atomic<int> ato2(ato.load()); //正确的,需要load函数来辅助
//ato.store(12); // 正确,用来赋值的操作。
}
//把收到的消息,入到一个队列中
void inMsgRecvQueue()
{
int i;
for (i = 0; i < 100000; ++i)
{
ato++;
//ato = ato + 1; //不是原子操作
}
}
//把数据从消息队列中取出
void outMsgRecvQueue()
{
while (true)
{
//
cout << "ato = " << ato << endl;
}
}
private:
list<int> msgQueue;
mutex my_mutex; //创建一个互斥量
std::condition_variable cond;
};
int main()
{
A myobj;
thread myOutMsg(&A::outMsgRecvQueue, std::ref(myobj)); //保证线程中用的同一个对象
thread myInMsg(&A::inMsgRecvQueue, std::ref(myobj));
thread myInMsg2(&A::inMsgRecvQueue, std::ref(myobj));
myOutMsg.join();
myInMsg.join();
myInMsg2.join();
cout << "main thread end..." << endl;
return 0;
}
posted on 2021-11-03 08:46 xcxfury001 阅读(25) 评论(0) 收藏 举报
浙公网安备 33010602011771号