Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep an Async Task

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;
}
like image 870
Rajeev Mehta Avatar asked Aug 22 '17 12:08

Rajeev Mehta


People also ask

What is the difference between task delay and thread sleep in C#?

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.

How do I stop async calls?

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.

What does an async task do?

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.


1 Answers

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(...).

like image 107
nwp Avatar answered Nov 06 '22 03:11

nwp