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

单个std::unique_lock搭配两次condition_variable.wait_for的问题排查

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();
    }    
}

问题解答

1. 线程t与主线程的运行顺序

主线程启动线程t后立即进入1秒睡眠;此时线程t开始执行,获取互斥锁mut后进入第一个cond.wait_for(等待期间会释放锁)。
主线程睡眠结束后,加锁将is_ok设为true,随后进入10秒睡眠——但主线程没有调用cond.notify_*通知条件变量,因此线程t会等待满3秒超时,此时检查谓词发现is_ok已满足,于是继续执行:打印ok 1,接着进入第二个wait_for,因is_ok已经为true,直接返回并打印ok 2,线程t终止。
主线程10秒睡眠结束后,调用join时线程t已结束,最终主线程退出。

2. 两次cond.wait_for调用是否均有效

两次调用均有效:

  • 第一次wait_for:线程t会等待满3秒超时(因主线程未通知条件变量),超时后检查谓词发现is_ok为true,因此返回true,不会执行wait 1的打印逻辑。
  • 第二次wait_for:由于is_ok已经是true,谓词直接满足,wait_for会立即返回true,无需进入等待状态。

3. 程序出现「Killed - processing time exceeded,Program terminated with signal: SIGKILL」错误的原因

主线程的总睡眠时长为1秒+10秒=11秒,加上线程t的执行时间,整个程序的运行时长超过了在线编译平台的默认运行时间限制(通常为10秒),因此被系统发送SIGKILL信号强制终止。

内容的提问来源于stack exchange,提问作者f1msch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:47:37