我已经阅读过有关在两个或多个线程之间发出信号的条件变量的信息。现在,我试图理解我拥有的一些代码,在此感谢您的帮助。我有(简体)
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
被称为再次
??我希望在此提供一些见识例如,假设put函数被调用并通知但没有线程在等待,因为尚未调用get。什么发生了吗?
文档说:*如果有任何线程在等待中
此,调用notify_one会解除阻塞其中一个正在等待的线程。 如果有],那么如果没有什么特别的事情发生。然后,假设get被调用并被阻止。还是没有? (理想情况下这不应该是因为已经有人先提出来了。]
将有条件地阻止到someCondition()
。如果someOperation()
导致实现someCondition()
,则在调用wait
时,notify_one()
将不受阻碍。