且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在多线程C ++应用程序中,我是否需要互斥体来保护简单的布尔值?

更新时间:2023-11-13 22:23:52

在具有标准定义的并发性的C ++ 11和更高版本中,请使用std::atomic<bool>来实现此目的.来自 http://en.cppreference.com/w/cpp/atomic/atomic:

In C++11 and later, which has standards-defined concurrency, use std::atomic<bool> for this purpose. From http://en.cppreference.com/w/cpp/atomic/atomic:

如果一个线程写入一个原子对象,而另一个线程读取一个原子对象,则该行为是明确定义的(有关数据竞争的详细信息,请参阅内存模型).

If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).


对于某些编译器和某些操作环境,以下旧答案在过去的某个时候可能是正确的,但今天不应该依赖它:


The following old answer may have been true at some time in the past with some compilers and some operating environments, but it should not be relied upon today:

您是正确的,在这种情况下,您不需要同步布尔值.不过,您应该声明它们volatile,以确保编译器每次实际上都从内存中读取它们,而不是将先前的读取缓存在线程中(这是一个简化的解释,但为此目的应该这样做).

You're right, in this case you won't need to synchronise the bools. You should declare them volatile though, to ensure that the compiler actually reads them from memory each time, instead of caching the previous read in a thread (that's a simplified explanation, but it should do for this purpose).

以下问题对此有更多信息: C ++线程,共享数据

The following question has more information about this: C++ Thread, shared data