std::async(std::launch::async, [&] () { std::this_thread::sleep_for( std::chrono::milliseconds{5000}); std::cout << "On TIMER!" << std::endl; } );
It does not work unless you assign the variable std::future returned by std::async variable and save it. I did not know why this was so, because I could not understand how it looked. Vincent Savard did and linked us to the destructor documentation for std::future , which states:
it can be blocked if all of them are true: the general state was created by calling std :: async, the general state is not ready yet, and this was the last link to the general state.
Since the returned std::future not attached to anything, it is instantly destroyed, and the destructor is blocked until completion.
I am going to leave the signal handler since it is not related to the problem.
#include <iostream> #include <future> int main() { auto letMeLive = std::async(std::launch::async, [] () { std::this_thread::sleep_for( std::chrono::milliseconds{5000}); std::cout << "On TIMER!" << std::endl; } ); std::cout << "main function" << std::endl; letMeLive.wait(); // instead of the signal handler return EXIT_SUCCESS; }
source share