简体   繁体   English

线程安全的局部变量

[英]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. 根据定义,原子操作不能重叠。

Can the local variable val be 1 in both threads? 两个线程中的局部变量val都可以为1吗?

No. ++static_counter is equivalent to: 不, ++static_counter相当于:

 fetch_add(1)+1

which cannot return same value for two (or more) threads because fetch_add is executed atomically. 因为 fetch_add是以原子方式执行的, 所以它不能为两个(或更多)线程返回相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM