我已经阅读了有关在两个或多个线程之间发出信号的条件变量的信息。现在,我试图理解我拥有的一些代码。我有(简体):
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()
,则在调用wait
时notify_one()
将被解除阻塞,如果已经实现someCondition()
,则odt不会被阻塞。
关于c++ - 试图了解条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61675979/