c ++应该在lock下通知条件变量 [英] c++ should condition variable be notified under lock

查看:136
本文介绍了c ++应该在lock下通知条件变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在www.cppreference.com上找到了条件变量的以下示例, http:/ /en.cppreference.com/w/cpp/thread/condition_variable 。对cv.notify_one()的调用放置在锁之外。我的问题是,如果调用应该在握住锁,以保证等待线程实际上处于等待状态,并将收到通知信号。

I found the following example for condition variable on www.cppreference.com, http://en.cppreference.com/w/cpp/thread/condition_variable. The call to cv.notify_one() is placed outside the lock. My question is if the call should be made while holding the lock to guarantee that waiting threads are in fact in waiting state and will receive the notify signal.

#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>

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<std::mutex> 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<std::mutex> lk(m);
        ready = true;
        std::cout << "main() signals data ready for processing\n";
    }
    cv.notify_one();

    // wait for the worker
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return processed;});
    }
    std::cout << "Back in main(), data = " << data << '\n';

    worker.join();
}

如果notify_one()调用在锁内移动,通知信号

Should the notify_one() call be moved inside the lock to guarantee waiting threads receive the notify signal,

// send data to the worker thread
{
    std::lock_guard<std::mutex> lk(m);
    ready = true;
    cv.notify_one();
    std::cout << "main() signals data ready for processing\n";
}


推荐答案

下锁。但是,由于通知在实际值发生变化时是逻辑上发生的(否则,为什么会通知?),并且变化必须在锁定下发生,通常在锁定内发生。

You do not need to notify under lock. However, since notify is logically happening when the actual value is changed (otherwise, why would you notify?) and that change must happen under lock, it is often done within the lock.

没有实际的观察差异。

这篇关于c ++应该在lock下通知条件变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆