当前位置: 首页 > news >正文

使用atomic实现无锁方式的全局变量访问

#include <atomic>
#include <thread>
#include <iostream>
using namespace std;atomic_uint32_t g_atomic_total = 0;
uint32_t g_total_non_atomic = 0;//线程函数,用于累加
void threadFunc(int64_t endNum) {for (int64_t i = 1; i <= endNum; ++i) {g_atomic_total += 1;g_total_non_atomic += 1;}
}int main() {int64_t endNum = 10000;thread t1(threadFunc, endNum);thread t2(threadFunc, endNum);t1.join();t2.join();cout << "total=" << g_atomic_total << endl;    //10100cout << "g_total_non_atomic=" << g_total_non_atomic << endl;    //10100
}

编译运行:

g++ atomic_int.cpp --std=gnu++1z -lpthread

http://www.dtcms.com/a/166635.html

相关文章:

  • 借助电商 API 接口实现电商平台商品数据分析的详细步骤分享
  • Python第四周作业
  • 力扣-数组-238 除自身以外数组的乘积
  • tbb parallel_for 使用教程2之 tbb::blocked_range
  • 【Android】Android签名解析
  • javascript 深拷贝和浅拷贝的区别及具体实现方案
  • 双指针(4)——盛水最多的容器
  • Vcpkg C++库管理工具安装
  • Depth Anything V2:深度万象 V2
  • 前端js学算法-实践
  • 可编辑25页PPT | 企业数字底座:数据中台构建路径、方法和实践
  • Vue3源码学习3-结合vitetest来实现mini-vue
  • Java ResourceBundle 资源绑定详解
  • linux find命令妙用
  • Kettle下载安装教程
  • Set系列之HashSet源码分析:原理剖析与实战对比
  • Ubuntu 24.04 终端美化
  • 强化学习之基于无模型的算法之基于值函数的深度强化学习算法
  • 望获实时Linux系统荣获人形机器人技术突破奖
  • 得物可观测平台架构升级:基于GreptimeDB的全新监控体系实践
  • 多通道经颅电刺激器的主流厂家介绍
  • 柯希霍夫积分法偏移成像中数据分布不均匀的处理方法
  • 【题解】Codeforces Round 1019 (Div. 2) B.Binary Typewriter ~ E.Keep the Sum
  • 【赵渝强老师】使用TiDB的审计日志
  • Learning vtkjs之ImageStreamline
  • URP - 公告牌的效果实现
  • 运维仙途 第2章 日志深渊识异常
  • 《多端统一的终极答案:X5内核增强版的渲染优化全解析》
  • AI赋能烟草工艺革命:虫情监测步入智能化时代
  • 栈与队列 Part 6