C++11 std::atomic
2021/7/15 22:07:22
本文主要是介绍C++11 std::atomic,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
什么是原子数据类型?
从功能上看,简单地说,原子数据类型不会发生数据竞争,能直接用在多线程中而不必我们用户对其进行添加互斥资源锁的类型。从实现上,大家可以理解为这些原子类型内部自己加了锁。
#include <thread> #include <atomic> #include <iostream> #include <list> using namespace std; // 使用原子类型 // atomic_int iCount(0); void threadFun1(void) { for (int i = 0; i < 1000; i++) { printf("iCount: %d\r\n", iCount++); } } void threadFun2(void) { for (int i = 0; i < 1000; i++) { printf("iCount: %d\r\n", iCount--); } } int main(void) { std::list<thread> lstThread; for(int i = 0; i < 100; i++) { lstThread.push_back(thread(threadFun1)); } for (int i = 0; i < 100; i++) { lstThread.push_back(thread(threadFun2)); } for (auto& th : lstThread) { th.join(); } int x = iCount.load(memory_order_relaxed); printf("finally iCount:%d\r\n", x); // return value return 0; }
运行结果:
不用原子类型数据:
#include <thread> #include <atomic> #include <iostream> #include <list> using namespace std; // 不用原子类型 int iCount = 0; void threadFun1(void) { for (int i = 0; i < 1000; i++) { printf("iCount: %d\r\n", iCount++); } } void threadFun2(void) { for (int i = 0; i < 1000; i++) { printf("iCount: %d\r\n", iCount--); } } int main(void) { std::list<thread> lstThread; for(int i = 0; i < 100; i++) { lstThread.push_back(thread(threadFun1)); } for (int i = 0; i < 100; i++) { lstThread.push_back(thread(threadFun2)); } for (auto& th : lstThread) { th.join(); } printf("finally iCount:%d\r\n", iCount); // return value return 0; }
运行结果:
小结:
Linux环境下运行,参数配置为:g++ -std=c++11 -pthread 14.atomictest.cpp
,结果均为一样!
这篇关于C++11 std::atomic的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-07fastcgi 是什么-icode9专业技术文章分享
- 2024-10-07fastcgi 的详细使用教程介绍-icode9专业技术文章分享
- 2024-10-07git如何更新单个文件到本地-icode9专业技术文章分享
- 2024-10-07如何使用ASM(Abstract Syntax Tree Manipulation)技术来修改第三方AAR依赖中的函数-icode9专业技术文章分享
- 2024-10-07Activity 跳转时间耗时很长怎么优化解决-icode9专业技术文章分享
- 2024-10-07Androud Toast 有哪些常用的第三方组件-icode9专业技术文章分享
- 2024-10-07在viewmodel中怎么使用 mmkv?-icode9专业技术文章分享
- 2024-10-07MMKV.defaultMMKV() 是单例模式吗?-icode9专业技术文章分享
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享