Raj*_*hta 4 c++ multithreading future c++11 c++14
在我的项目中,我需要每隔n秒轮询一些设备并睡眠并永远继续.我创建了一个async任务,启动为async而不是std::thread.但是如果我std::this_thread::sleep_for()在异步任务中使用启动async,看起来它实际上阻止了我的主线程?以下程序永远输出"Inside Async ..",它永远不会打印"Main function".
如果我使用a 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;
}
Run Code Online (Sandbox Code Playgroud)
std::async返回一个std::future等待任务在其析构函数中完成的a.保存在std::future某处以延迟析构函数:
auto future = std::async(...).