[英]condition_variable::wait_for always waits?
I have some code in a unit test that waits until my vector is sufficiently big: 我在单元测试中有一些代码,等待我的向量足够大:
bool waitForOutwardMessages(size_t size, int millis) {
std::unique_lock<std::mutex> lock(mutex);
return ready.wait_for(lock, std::chrono::milliseconds(millis), [=]{
return this->messages.size() >= size;
});
}
std::mutex mutex;
std::condition_variable ready;
Easy enough. 很简单。 Except when I run this test, I'm expecting that the the vector in question should fill up on the order of milliseconds after I make this call on the other thread.
除了运行该测试时,我期望在其他线程上执行此调用后,所涉及的向量应以毫秒为单位填充。 Maybe 10ms, maybe 100ms, certainly within 1s.
也许10毫秒,也许100毫秒,肯定在1秒钟之内。 But when I pass in 5000 as the
millis
argument, this function always waits 5 seconds. 但是当我传入5000作为
millis
参数时,此函数总是等待5秒。
On the one hand, this is fine, because I don't care how long this test takes anyway. 一方面,这很好,因为我不在乎此测试需要花费多长时间。 On the other hand, I thought it was supposed to wait up to the duration only if the condition variable wasn't notified... not always?
另一方面,我认为只有在未通知条件变量的情况下才应等待持续时间……不是总是这样吗?
Is there a way to get this to return earlier? 有没有办法让它早日返回?
Check that you are actually calling signal or broadcast on ready
. 检查您是否正在实际呼叫信号或
ready
广播。 There's a possible race if you're not careful where you can signal the condition before you actually wait on it (which will cause a wait until timeout). 如果您不小心在实际等待条件之前可以在何处发出信号(可能会导致超时),这可能会导致比赛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.