简体   繁体   English

使用“常规”变量来同步线程

[英]Use “regular” variable to synchronize threads

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;

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. 我假设对单个bool的读取或写入是原子的,即使不是,我也看不出它如何在这里有所作为。

No, it can't work. 不,它不起作用。 If you use std::atomic<bool> instead it will work. 如果使用std::atomic<bool> ,它将起作用。

Atomics in C++ address three issues. C ++中的原子解决了三个问题。 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. 第三,由于顺序无关紧要,编译器可能会移动代码。

Even though a bool value probably only requires one bus cycle to read or write, it doesn't address the other two issues. 即使bool值可能只需要一个总线周期即可读取或写入,但它不能解决其他两个问题。

There are no reliable shortcuts. 没有可靠的快捷方式。 Use proper synchronization. 使用适当的同步。

While you would get guarantees with an std::atomic<bool> , I think you could perhaps make it work with a simple volatile , because: 虽然您可以使用std::atomic<bool>获得保证,但我认为您可以使它与简单的volatile ,因为:

  • the compiler cannot reorder instructions on volatile values 编译器无法对volatile值的指令重新排序
  • one of the threads always write to the variable, so the instruction is effectively atomic 线程之一总是写入变量,因此指令实际上是原子的
  • the other thread doesn't need to do the read and the write atomically 另一个线程不需要原子地进行读取和写入

So there wouldn't be any form of tearing. 因此,不会有任何形式的眼泪。 However, the issue of cache coherency is still there, and that's hardware or OS dependent. 但是,缓存一致性的问题仍然存在,并且这取决于硬件或操作系统。

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

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