且构网

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

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

更新时间:2023-11-13 22:59:04

在具有标准定义并发的 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