stdthread(5)并发atomic
生活随笔
收集整理的这篇文章主要介绍了
stdthread(5)并发atomic
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1. 原子数据类型
不会发生数据竞争,能直接用在多线程中而不必我们用户对其进行添加互斥资源锁的类型。
在现代 CPU 体系结构下提供了 CPU 指令级的原子操作, std::atomic 模板使得我们实例化一个原子类型,将一个 原子类型读写操作从一组指令,最小化到单个 CPU 指令。
//c11.cpp #include <thread> #include <atomic> #include <stdio.h> #include <iostream> #include <list> std::atomic<bool> bIsReady(false); std::atomic<int> iCount(10); void threadfun1() {if (!bIsReady) {std::this_thread::yield();}while (iCount > 0){printf("iCount:%d\r\n", iCount--);} } int main() {std::list<std::thread> lstThread;for (int i = 0; i < 10; ++i){lstThread.push_back(std::thread(threadfun1));}for (auto& th : lstThread){th.join();} }总结
以上是生活随笔为你收集整理的stdthread(5)并发atomic的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: STL源代码分析(ch2 内存分配)de
- 下一篇: stdthread(6)并发mutex