在条件变量上调用notify时,互斥锁是否会被解锁

dan*_*nny 10 c++ condition-variable c++11

我试图了解在互斥锁用于条件变量时会发生什么.

在以下示例中,取自cppreference

int main()
{
    std::queue<int> produced_nums;
    std::mutex m;
    std::condition_variable cond_var;
    bool done = false;
    bool notified = false;

    std::thread producer([&]() {
        for (int i = 0; i < 5; ++i) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            std::unique_lock<std::mutex> lock(m);
            std::cout << "producing " << i << '\n';
            produced_nums.push(i);
            notified = true;
            cond_var.notify_one();
        }   

        done = true;
        cond_var.notify_one();
    }); 

    std::thread consumer([&]() {
        std::unique_lock<std::mutex> lock(m);
        while (!done) {
            while (!notified) {  // loop to avoid spurious wakeups
                cond_var.wait(lock);
            }   
            while (!produced_nums.empty()) {
                std::cout << "consuming " << produced_nums.front() << '\n';
                produced_nums.pop();
            }   
            notified = false;
        }   
    }); 

    producer.join();
    consumer.join();
}
Run Code Online (Sandbox Code Playgroud)

生产者线程在互斥锁解锁之前调用cond_var.notify_one().在调用notify时,互斥锁m是否会被解锁,或者只有在互斥锁被解锁时才会发生通知?

Joh*_*ica 10

通知不会解锁互斥锁.您可以(间接)告诉您,因为您没有notify_one()按照您的方式传递锁定wait(),这会在等待时释放互斥锁.

另一方面,通知的线程 "立即"通知.但他们不一定会wait()马上回来.在他们返回之前,wait()他们必须首先重新获取互斥锁,因此他们将阻止那里直到通知线程释放它.