I have the following very simple code:
void TestSleep()
{
std::cout << "TestSleep " << std::endl;
sleep(10);
std::cout << "TestSleep Ok" << std::endl;
}
void TestAsync()
{
std::cout << "TestAsync" << std::endl;
std::async(std::launch::async, TestSleep);
std::cout << "TestAsync ok!!!" << std::endl;
}
int main()
{
TestAsync();
return 0;
}
Since I use std::launch::async
I expect that TestSleep()
will be run asynchronously and I will have the following output:
TestAsync
TestAsync ok!!!
TestSleep
TestSleep Ok
But really I have the output for synchronous run:
TestAsync
TestSleep
TestSleep Ok
TestAsync ok!!!
Could you explain why and how to make TestSleep
call really asynchronously.
std::async()
returns an instance ofstd::future
. If you look at the documentation forstd::future
's destructor, it says the following:You aren't storing the return value of
std::async()
into a local variable, but that value is still created and must be destroyed. Since the destructor will block until your function returns, this makes it synchronous.If you change
TestAsync()
to return thestd::future()
created bystd::async()
, then it should be asynchronous.From this
std::async
reference notes sectionThis is what happens here. Since you don't store the future that
std::async
returns, it will be destructed at the end of the expression (which is thestd::async
call) and that will block until the thread finishes.If you do e.g.
then the destruction of
f
at the end ofTestAsync
will block, and the text"TestAsync ok!!!"
should be printed before"TestSleep Ok"
.