【发布时间】:2017-08-22 12:27:53
【问题描述】:
在我的项目中,我需要每隔 n 秒轮询一些设备,然后休眠并永远继续。我创建了一个异步任务,启动为异步而不是std::thread。但是,如果我在异步任务中使用 std::this_thread::sleep_for() 并以异步方式启动,看起来它实际上阻塞了我的主线程?
以下程序永远输出“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;
}
【问题讨论】:
-
如果你只是简单地分离一个线程,你“不必再加入它并管理它的生命周期”了。
-
曾经有段时间我们为此使用了documentation。
-
@samvar 如果您希望程序干净地终止,那么分离并不简单。
标签: c++ multithreading c++11 c++14 future