#include<iostream>
#include<thread>
#include<atomic>//包含了很多原子类型
#include<list>
using namespace std;
/*
* C++11
* 卖票窗口 int count =100;
* lock_guard<std::mutex> guard(mtx)
* count++
* lock_guard<std::mutex> guard(mtx)
* conut--
* 互斥锁比较重,临界区代码多的事情稍稍复杂,多
* 系统理论:CAS来保证上面++--操作的原子特性就足够了,无锁操作.
* 无锁队列->是通过CAS来实现的.
*/
volatile std::atomic_bool isReady = false;
volatile std::atomic_int mycount = 0;
void funadd()
{
while (!isReady)
{
std::this_thread::yield();//线程出让当前的cpu时间片,等待下一次调度
}
for (int i = 0; i < 100; i++)
{
mycount++;
}
}
int main()
{
list<std::thread> listThread;
for (int i = 0; i < 10; i++)
{
listThread.push_back(std::thread(funadd));
}
std::this_thread::sleep_for(std::chrono::seconds(3));
isReady = true;
for (std::thread& t : listThread)
{
t.join();
}
cout << "mycount is " << mycount << endl;
return 0;
}
学习笔记:原子类型
原创
©著作权归作者所有:来自51CTO博客作者OneDbZero的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:学习笔记:模拟卖票系统
下一篇:学习笔记:适配器模式
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
HarmonyOS NEXT 学习笔记
鸿蒙os 页面一键置灰
页面效果 API