gpt4 book ai didi

c++ - 休眠一个异步任务

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:33 29 4
gpt4 key购买 nike

在我的项目中,我需要每 n 秒轮询一些设备并休眠并永远继续。我已经创建了一个异步任务,启动为异步而不是 std::thread。但是,如果我在异步任务中使用 std::this_thread::sleep_for() 启 Action 为异步,看起来它实际上阻塞了我的主线程?以下程序永远输出“Inside Async..”,它从不打印“Main function”。

如果我不使用异步,而是使用 std::thread(),它会工作正常。但我想使用异步任务,因为我不必像线程那样加入它并管理它的生命周期。

如何让异步任务休眠?

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

int main()
{
std::async(std::launch::async,
[]()
{
while(true)
{
std::cout <<"Inside async.."<< std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
}
});

std::cout <<"Main function"<< std::endl;
return 0;
}

最佳答案

std::async 返回一个 std::future 等待任务在其析构函数中完成。将 std::future 保存在某处以延迟析构函数:

auto future = std::async(...)

关于c++ - 休眠一个异步任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45817661/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com