c++ - 试图了解条件变量

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

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

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不为true,它将阻塞。一旦收到信号,它将执行其他一些操作并返回其值。
我不明白的是时间。
例如,假设put函数被调用并通知,但没有线程在等待,因为尚未调用get。怎么了?
然后,假设get被调用并阻塞了。还是没有? (理想情况下不应该这样,因为已经有人先调用了put)。get是否应该等待直到再次调用put

最佳答案

For example let's say that the put function is called and it notifies but no thread is waiting because get has not been called. What happens?



docs说:*如果有任何线程正在等待,则调用notify_one会解除阻塞其中一个正在等待的线程。 如果有,则没有什么特别的事情发生。

Then let's say get gets called and it blocks. Or it doesn't?? (ideally it shouldn't because someone already called put first).



它将有条件地限制为someCondition()。如果someOperation()导致实现someCondition(),则在调用waitnotify_one()将被解除阻塞,如果已经实现someCondition(),则odt不会被阻塞。

关于c++ - 试图了解条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61675979/

相关文章:

c++ - 模板参数推导 : which compiler is right here?

c++ - Eclipse、minGW 和 C++11

c++ - 以度而不是弧度计算三角函数

c++ - 为什么在浮点文字的末尾添加 0 会改变它的舍入方式(可能是 GCC 错误)?

c++ - 我如何将指令传递给 intel-pintool 中的回调?

C# 线程 - 锁 - 如何检查锁的发生

multithreading - 接收器在尝试通过 channel 发送时关闭并返回 SendError

java - Apache Ignite 中单个分区上的 ScanQuery 是单线程还是多线程?

c++ - 有没有办法使 unique_ptr 的实例化不那么冗长?

c++ - QTimer::timeout 没有触发