博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++11使用atomic多线程同步3种方法
阅读量:4092 次
发布时间:2019-05-25

本文共 1692 字,大约阅读时间需要 5 分钟。

// 使用CAS实现多线程无锁访问共享变量,达到线程同步# include 
# include
# include
# include
using namespace std;std::atomic
var(0);void add() {
int expect = var; while (!atomic_compare_exchange_weak(&var, &expect, var + 1));}int main(int argc, char *argv[]) {
int count = 2000; std::thread threads[count]; for (int i = 0; i < count; ++i) threads[i] = std::thread(add); for (int i = 0; i < count; ++i) threads[i].join(); cout << var << endl; // var 为 2000,无误!! return 0;}

// 使用原子数据类型的原子方法操作,达到同步线程# include 
# include
# include
# include
using namespace std;std::atomic
var(0);void add() {
var.fetch_add(1); // cout << std::boolalpha ; // cout << "is_lock_free:" << var.is_lock_free() << endl; // true}int main(int argc, char *argv[]) {
int count = 2000; std::thread threads[count]; // default-constructed threads for (int i = 0; i < count; ++i) threads[i] = std::thread(add); for (int i = 0; i < count; ++i) threads[i].join(); cout << var << endl; return 0;}

// 使用RAII的mutex,同步线程# include 
# include
# include
# include
using namespace std;std::mutex mtx;void add(int *var) {
std::lock_guard
l(mtx); (*var)++;}int main(int argc, char *argv[]) {
int count = 2000; std::thread threads[count]; // default-constructed threads int *var = new int [1]; for (int i = 0; i < count; ++i) threads[i] = std::thread(add, var); for (int i = 0; i < count; ++i) threads[i].join(); cout << *var << endl; return 0;}

转载地址:http://aecii.baihongyu.com/

你可能感兴趣的文章
小程序实现列表无限滚动加载的详细步骤
查看>>
小程序使用echarts封装成自定义组件的实现方法
查看>>
微信小程序如何在父组件中修改子组件的样式
查看>>
小程序返回上一页面,如何实现刷新效果
查看>>
vscode中vue项目 template注释错误的问题
查看>>
判断对象中的属性是否都有值
查看>>
小程序中时间比较的坑
查看>>
将本地项目推送到码云远程的基本步骤
查看>>
Eslint报错含义及解决方案汇总
查看>>
小程序中快速删除所有编译模式的方法
查看>>
微信小程序 弹出层 禁止页面滚动的方法
查看>>
蓝绿部署、滚动发布和灰度发布浅析
查看>>
什么是微前端架构?它有什么优缺点以及构建思路
查看>>
涨知识啦:css粘性定位position:sticky
查看>>
前端开发必知:组件封装的原则
查看>>
微信小程序采坑记录:http:XXX 不在以下request合法域名列表中的解决方法
查看>>
js数组去重小结
查看>>
javascript defer与async 的差异
查看>>
flex实现等宽布局且间隔相等的小技巧
查看>>
JS冷知识:label 语句记录循环语句中断的值
查看>>