试图理解条件变量

问题描述 投票:0回答:1

我已经阅读过有关在两个或多个线程之间发出信号的条件变量的信息。现在,我试图理解我拥有的一些代码,在此感谢您的帮助。我有(简体)

class Class{
    void put(Something&& something){
        {
            std::lock_guard<std::mutex> lock(a_mutex);
            // Do the operation here
            some_operation();
        }
        cond_var.notify_one();
    }

    std::unique_ptr<Something> get(){
        std::unique_lock<std::mutex> lock(a_mutex);

        cond_var.wait(lock,[this]{return someCondition()});

        //Do the operation here
        auto res=some_other_operation();
        return res;
    }

    std::mutex a_mutex;
    std::condition_variable cond_var;    
};

我可以理解,put获得了一个锁并执行了一些操作,然后通知任何等待解除阻塞的线程。 get也会阻塞,直到条件变量被put发出信号为止;否则,如果someCondition不为真,则阻塞。一旦收到信号,它将执行其他一些操作并返回其值。

我不知道是时间。

例如,假设put函数被调用并通知,但没有线程在等待,因为尚未调用get。会发生什么?

然后假设get被调用并阻塞。还是没有? (理想情况下,它是[[不应,因为有人已经先打电话给put)。

应该get等到put被称为

再次

??我希望在此提供一些见识
c++ multithreading c++11 condition-variable
1个回答
1
投票
例如,假设put函数被调用并通知但没有线程在等待,因为尚未调用get。什么发生了吗?

文档说:*如果有任何线程在等待中

此,调用notify_one会解除阻塞其中一个正在等待的线程。 如果有],那么如果没有什么特别的事情发生。

然后,假设get被调用并被阻止。还是没有? (理想情况下这不应该是因为已经有人先提出来了。]

将有条件地阻止到someCondition()。如果someOperation()导致实现someCondition(),则在调用wait时,notify_one()将不受阻碍。

© www.soinside.com 2019 - 2024. All rights reserved.