In my project I need to poll some devices every n seconds and sleep and continue forever. I have created an async task with launch as async instead of std::thread
. But if I use std::this_thread::sleep_for()
inside an async task with launch as async, it looks like its actually blocking my main thread?
The following program outputs "Inside Async.." forever, it never prints "Main function".
Instead of async, if I use a std::thread()
, it would work fine. But I wanted to use an async task as I don't have to join it and manage its lifetime unlike a thread.
How do I make an async task sleep?
#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;
}