Delayed Function Call

Nordlöw picture Nordlöw · May 29, 2012 · Viewed 9.1k times · Source

What's the most elegant way of performing a delayed (and therefore also asynchronous) functional call using C++11, lambdas and async? Suggested naming: delayed_async. Reason for asking is that I want a GUI alert light to be switched off after given time (in this case one second) without blocking the main (wxWidgets main loop) thread of course. I've use wxWidgets' wxTimer for this and I find wxTimer rather cumbersome to use in this case. So that got my curious about how much more convenient this could be implemented if I instead used C++11's async1, 2. I'm aware of that I need to protect the resources involved with mutexes, when using async.

Answer

KillianDS picture KillianDS · May 29, 2012

You mean something like this?

#include <iostream>
#include <chrono>
#include <thread>
#include <future>

int main()
{
    // Use async to launch a function (lambda) in parallel
    std::async(std::launch::async, [] () {
        // Use sleep_for to wait specified time (or sleep_until).
        std::this_thread::sleep_for( std::chrono::seconds{1});
        // Do whatever you want.
        std::cout << "Lights out!" << std::endl;
    } );
    std::this_thread::sleep_for( std::chrono::seconds{2});
    std::cout << "Finished" << std::endl;
}

Just make sure that you don't capture a variable by reference in the lambda.