g++9.4.0中condition_variable::wait_until意外直接返回问题分析
std::condition_variable::wait_until 行为差异问题
我在研究std::condition_variable::wait_until的行为时,编写了两段预期会等待1秒后退出的代码,但在g++9.4.0(libc6 2.3.2)环境下执行时,第一段代码未等待直接退出,第二段则正常等待。
第一段未等待的代码
编译命令:g++ foo_passes_thru.cpp
// foo_passes_thru.cpp // I compiled with `g++ foo_passes_thru.cpp` #include <chrono> #include <mutex> #include <condition_variable> std::condition_variable cv; std::mutex m; int main(int argc, char * argv[]) { using namespace std::chrono_literals; std::unique_lock<std::mutex> lk(m); const auto now = std::chrono::high_resolution_clock::now(); cv.wait_until(lk, now + 1000ms); return 0; }
第二段正常等待的代码
编译命令:g++ foo_waits_1sec.cpp -lpthread
// foo_waits_1sec.cpp // I compiled with `g++ foo_waits_1sec.cpp -lpthread` #include <chrono> #include <mutex> #include <condition_variable> #include <thread> std::condition_variable cv; std::mutex m; int main(int argc, char * argv[]) { using namespace std::chrono_literals; std::thread causes_wait([]{}); // don't even need the thread to run causes_wait.join(); std::unique_lock<std::mutex> lk(m); const auto now = std::chrono::high_resolution_clock::now(); cv.wait_until(lk, now + 1000ms); return 0; }
观察发现
- 两段代码编译后的
wait_until实现无明显差异 - 最终都会调用
pthread_cond_timedwait
我不确定这属于未定义行为,还是g++/STL/pthread存在问题,pthread_cond_timedwait的文档未提及该差异。
更新
发布后发现相关问题:为第一段代码添加-pthread编译选项即可恢复预期行为,两段代码都应使用该选项编译。
内容的提问来源于stack exchange,提问作者stephematician
相关产品推荐
相关产品推荐

