如果代码像
std::mutex mut;
std::condition_variable cond;
bool is_ok = false;
void func() {
std::unique_lock<std::mutex> lck(mut);
if (!cond.wait_for(lck,
std::chrono::seconds(3),
[&] { return is_ok; })) {
std::cout << "wait 1" << std::endl;
}
std::cout << "ok 1" << std::endl;
if (!cond.wait_for(lck,
std::chrono::seconds(8),
[&] { return is_ok; })) {
std::cout << "wait 2" << std::endl;
}
std::cout << "ok 2" << std::endl;
}
int main(){
std::thread t(func);
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lck(mut);
is_ok = true;
}
std::this_thread::sleep_for(std::chrono::seconds(10));
if (t.joinable()){
t.join();
}
}
那么
thread t
和main thread
之间的运行顺序是什么呢?
两个cond.wait_for
都有效吗?
此外,程序因一些错误而结束
Killed - processing time exceeded
Program terminated with signal: SIGKILL
它从哪里来?
是的,您当然可以在条件变量的生命周期内多次使用
wait_for
,并且可以重用同一个锁对象。
但是您似乎误解了条件变量的工作原理,因为您从未发出信号(通过从主线程调用
notify_one
或 notifiy_all
)。所以你的等待尝试就会超时。
由于 godbolt 将程序的执行时间限制为远小于您总共睡眠的 11 秒,因此您的工作就会被终止。您应该在本地计算机上进行这样的测试。