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;
}
delays did not cause thread jumps. And all of this research is to propose: while thread. sleep will block a thread and task. delay will not and has a cancellation token, unless your app is pretty complex, it really doesn't matter as on the surface: task.
You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.
An async method runs synchronously until it reaches its first await expression, at which point the method is suspended until the awaited task is complete. In the meantime, control returns to the caller of the method, as the example in the next section shows.
std::async
returns a std::future
which waits for the task to finish in its destructor. Save the std::future
somewhere to delay the destructor:
auto future = std::async(...)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With