[英]Thread safe local variable
void HelloWorld()
{
static std::atomic<short> static_counter = 0;
short val = ++static_counter; // or val = static_counter++;
}
If this function is called from two threads, 如果从两个线程调用此函数,
Can the local variable val
be 1
in both threads? 两个线程中的局部变量val
都可以为1
吗? or (0 if static_counter++
is used?) 或(如果使用static_counter++
则为0?)
No. The only way val
could have the same value in both threads is if the two atomic operations overlapped. 否。在两个线程中, val
可以具有相同值的唯一方法是两个原子操作重叠。 By definition, atomic operations cannot overlap. 根据定义,原子操作不能重叠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.