2
原子操作和atomic关键字
source link: https://charon-cheung.github.io/2022/05/18/C++/%E5%A4%9A%E7%BA%BF%E7%A8%8B/%E5%8E%9F%E5%AD%90%E6%93%8D%E4%BD%9C%E5%92%8Catomic%E5%85%B3%E9%94%AE%E5%AD%97/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
原子操作和atomic关键字 | 沉默杀手
std::atomic
//int v = 0;
std::atomic<int> v(0);
void Test()
{
for(int i=0; i<10000; i++)
++v;
}
int main(int argc, char *argv[])
{
std::thread t1(Test);
std::thread t2(Test);
t1.join();
t2.join();
std::cout << "v: " << v << std::endl;
return 0;
}
如果只用简单的全局变量int v = 0;
,结果一般不是20000。 换上std::atomic<int> v(0);
,结果必为20000
参考:
Item40 Use std::atomic for concurrency
聊一聊原子操作
C++11多线程编程详解
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK