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

C++11中如何避免sleep_for阻塞后台线程?

如何避免this_thread::sleep_for阻塞后台线程?

首先得澄清一个关键点:this_thread::sleep_for本身就是让当前线程(也就是你通过async启动的后台线程)进入休眠状态,这是它的设计目的——后台线程休眠期间不会占用CPU时间,也不会阻塞主线程或其他线程。

但你的代码现在有个隐藏问题:它会意外阻塞主线程8秒,原因不是sleep_for,而是你没有保存std::async返回的std::future对象。当std::async返回的future是临时对象时,它的析构函数会等待后台线程完全执行完毕才会返回,这就导致主线程在执行完async那一行后,会卡在那里直到sleep_for结束,才会执行后面的cout << "i'm here" << endl;。

解决方法:保存std::future对象

只要把async的返回值用变量存起来,就能避免主线程被阻塞:

#include <iostream>
#include <future>
#include <thread>
#include <chrono>

// 假设这是你的类成员代码
std::atomic<bool> animating{true}; // 建议用atomic避免数据竞争

void yourFunction() {
    std::cout << "stop animating!" << std::endl;
    this->animating = false;
    
    // 保存future对象,防止临时对象析构时等待线程完成
    auto anim_future = std::async(std::launch::async, [this] () {
        std::this_thread::sleep_for(std::chrono::seconds{8});
        this->animating = true;
        std::cout << "start animating!" << std::endl;
    });
    
    std::cout << "i'm here" << std::endl;
    // 如果后续不需要和这个线程交互,anim_future可以不用管,线程会在后台自行完成
}

额外注意事项:线程安全的变量访问

因为animating被主线程和后台线程同时读写,强烈建议把它声明为std::atomic<bool>,这样可以避免数据竞争导致的未定义行为。普通的bool变量在多线程环境下的读写操作不是原子的,可能会出现意想不到的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:27:08