使用“常规"用于同步线程的变量

2022-01-22 00:00:00 multithreading synchronization c++

如果我只有两个线程,并且我希望其中一个等待另一个达到某个点,那么执行以下操作是否安全:

If I have only two threads, and I want one of them to wait for the other to reach a certain point, is it safe to do the following:

bool wait = true;

//Thread 1:
while(wait) ;
wait = true; //re-arm the signal

//Thread 2:
/* Preform here the code that needs to complete before Thread 1 continues */
wait = false;

基本上,如果一个线程只写,另一个只读,会不会有问题?我假设单个 bool 的读取或写入是原子的,即使不是,我也看不出它在这里有何不同.

Basically, if one thread only writes to it and the other only reads, can there be a problem? I assume a read or a write of a single bool is atomic, and even if not, I don't see how it can make a difference here.

推荐答案

不行,不行.如果你使用 std::atomic<bool> 代替它会工作.

No, it can't work. If you use std::atomic<bool> instead it will work.

C++ 中的原子解决了三个问题.第一,在存储或读取需要多个总线周期的值的过程中发生线程切换的可能性;这被称为撕裂".其次,两个线程可能会在两个具有两个独立缓存的独立处理器上运行,并且一个线程不会看到另一个线程所做的更改.这称为缓存一致性".第三,编译器可能会移动代码,因为顺序似乎无关紧要.

Atomics in C++ address three issues. First, the possibility that a thread switch will happen in the middle of storing or reading a value that requires more than one bus cycle; this is called "tearing". Second, the possibility that two threads will be running on two separate processors with two separate caches, and one thread won't see changes made by the other. This is called "cache coherency". Third, the possibility that the compiler will move code around because the order doesn't appear to matter.

尽管 bool 值可能只需要一个总线周期来读取或写入,但它并不能解决其他两个问题.

Even though a bool value probably only requires one bus cycle to read or write, it doesn't address the other two issues.

没有可靠的捷径.使用适当的同步.

There are no reliable shortcuts. Use proper synchronization.

相关文章