【发布时间】:2015-04-16 19:34:38
【问题描述】:
考虑到创建/加入线程时的隐含同步:std::atomic 时,x 的类型需要什么最小帧才能工作? volatile?什么都没有?
#include <thread>
#include <cassert>
int main() {
int x = 123; // ***
std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();
assert( x == 321 );
return 0;
}
【问题讨论】:
-
您需要阅读this answer 来了解相关问题。
-
std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();x没有并发访问,您可以按顺序调用 lambda 以实现相同的行为。volatile从不用于线程安全,顺便说一句。
标签: c++ multithreading language-lawyer memory-model