C++条件变量为什么需要锁?

Tyl*_*ler 3 c++ multithreading condition-variable c++11 c++20

在参考文档中std::condition_variable有这个例子:

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
 
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
 
void worker_thread()
{
    // Wait until main() sends data
    std::unique_lock lk(m);
    cv.wait(lk, []{ return ready; });
 
    // after the wait, we own the lock.
    std::cout << "Worker thread is processing data\n";
    data += " after processing";
 
    // Send data back to main()
    processed = true;
    std::cout << "Worker thread signals data processing completed\n";
 
    // Manual unlocking is done before notifying, to avoid waking up
    // the waiting thread only to block again (see notify_one for details)
    lk.unlock();
    cv.notify_one();
}
 
int main()
{
    std::thread worker(worker_thread);
 
    data = "Example data";
    // send data to the worker thread
    {
        std::lock_guard lk(m);
        ready = true;
        std::cout << "main() signals data ready for processing\n";
    }
    cv.notify_one();
 
    // wait for the worker
    {
        std::unique_lock lk(m);
        cv.wait(lk, []{ return processed; });
    }
    std::cout << "Back in main(), data = " << data << '\n';
 
    worker.join();
}
Run Code Online (Sandbox Code Playgroud)

我的问题非常具体地涉及这一部分:

    {
        std::lock_guard lk(m);
        ready = true;
        std::cout << "main() signals data ready for processing\n";
    }
    cv.notify_one();
Run Code Online (Sandbox Code Playgroud)

为什么ready需要有锁卫?如果另一个线程正在等待,难道不应该保证ready = true在另一个线程被唤醒之前发生吗notify_one

我要求这个问题是为了深入了解我看到的一个无法在此处显示的私有代码库的问题。

我更困惑如果ready是一个std::atomic那么锁还需要吗?在私有代码中,我观察到它仍然如此,否则在通知和唤醒发生之前布尔值不会改变

Ted*_*gmo 5

如果没有相关锁,ready = true;则不会与worker_thread读取同步ready。这是一场数据竞争并且具有未定义的行为

    {
        // std::lock_guard lk(m); // removed
        ready = true;             // race condition
    }
Run Code Online (Sandbox Code Playgroud)

通过删除同步原语,对ready一个线程中的更改不需要编译器生成任何对程序员有意义的代码。

等待线程可能永远不会看到更改ready,编译器可能会让等待线程观察“缓存”值false- 因为您没有告诉编译器需要一些同步。如果两个线程不同步,那么为什么编译器应该假设变量的值在读取它的线程中会发生变化?如果您不告诉它有一个编写器,它可能会简单地将变量的读取替换为硬值,true无论是它还是false

编译器还可以布置最终的程序集,就好像ready一直在设置一样。当您不同步事件时,它可以以任何方式运行。

您也不知道等待线程何时醒来。它不仅可能被唤醒,notify_one因为还存在虚假唤醒,这就是为什么唤醒后必须检查情况。如果不是true,则返回等待。