You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:20:50