【发布时间】:2020-05-08 09:24:44
【问题描述】:
我已经阅读了有关在两个或多个线程之间发出信号的条件变量。现在我试图理解我拥有的一些代码。我有(简化):
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