【问题标题】:Does a mutex get unlocked when calling notify on a condition variable?在条件变量上调用通知时,互斥锁是否会解锁?
【发布时间】:2012-10-22 20:33:52
【问题描述】:

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

在以下示例中,取自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();
}

生产者线程在互斥锁解锁之前调用cond_var.notify_one()。调用 notify 时 mutex m 是否解锁,还是仅在 mutex 解锁时才通知?

【问题讨论】:

    标签: c++ c++11 condition-variable


    【解决方案1】:

    通知不会解锁互斥锁。您可以(间接地)知道,因为您没有将锁传递给notify_one(),就像您传递给wait() 的方式一样,它确实在等待时释放了互斥锁。

    另一方面,通知线程“立即”通知。但他们不一定会立即从wait() 返回。在他们可以从wait()返回之前,他们必须首先重新获取互斥锁,所以他们会在那里阻塞直到通知线程释放它。

    【讨论】:

      【解决方案2】:

      锁在构造函数中被获取,在std::unique_lock的析构函数中被释放。从这个信息可以推断出生产者在调用notify_one()完成后释放了锁。

      【讨论】:

      • 正是要寻找的东西:D
      【解决方案3】:

      出于性能原因,我建议在通知其他线程之前解锁互斥锁。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-06
        • 1970-01-01
        • 2021-10-16
        相关资源
        最近更新 更多