创建/加入线程时的隐式同步 [英] Implicit synchronization when creating/joining threads
问题描述
考虑到创建/加入线程std::atomic
时隐式的同步,x
类型的此代码起作用所需的 minimum 框架是什么? volatile
?什么都没有?
What is the minimal framing required for x
's type for this code to work, considering the implied synchronization when creating/joining a thread: std::atomic
? volatile
? nothing?
#include <thread>
#include <cassert>
int main() {
int x = 123; // ***
std::thread( [ & ] { assert( x == 123 ); x = 321; } ).join();
assert( x == 321 );
return 0;
}
推荐答案
std::thread
的构造函数的调用是同步的,并且发生在调用线程函数的副本(30.3.1.2/6)之前.
The invocation of std::thread
's constructor is synchronized and happens before the invocation of the copy of the thread function (30.3.1.2/6).
thread::join
提供了类似的同步保证:线程的完成发生在join
返回(30.3.1.4/7)之前.
thread::join
gives a similar synchronization guarantee: The completion of the thread happens before join
returns (30.3.1.4/7).
您的代码创建一个线程并立即将其加入.尽管您的lambda是通过引用捕获的,但没有并发性(代码按顺序运行),并且std::thread
提供的保证确保您不需要任何特殊的框架来保护x
.断言永远不会失败.
Your code creates a thread and joins it immediately. Although your lambda captures by reference, there is no concurrency (the code runs as-if sequential), and the guarantees provided by std::thread
make sure that you do not need any special framing to guard x
. The assertion will never fail.
假设您的代码段不同,因此您实际上具有某种并发访问权限,则必须使用std::atomic
或互斥锁. volatile
肯定不是足够的(巧合除外).
Assuming your code snippet was different so you actually have concurrent access of some kind, you would have to use std::atomic
or a mutex. volatile
would most definitively not be enough (except by coincidence).
这篇关于创建/加入线程时的隐式同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!