I am testing on the std::async function with the code from http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-8-futures-and-promises.html
int calculate_the_answer_to_LtUaE(){
sleep(5);
cout << "Aaa" << endl;
}
std::future<int> the_answer=std::async(calculate_the_answer_to_LtUaE);
the_answer.get();
cout << "finish calling" << endl;
sleep(10000);
I need to call the_answer.get() to invoke calculate_the_answer_to_LtUaE() and get the Aaa printed on the screen. If I commented out the_answer.get() line, I would not get anything printed. Is this the intended behaviour of the std::async function or I am doing something wrong here? This is because I thought the_answer.get() is used to wait for the function to complete and to retrieve the result.
Thanks.
If you read the section of the thing you linked to about 'launch policies' you'll see that I'm exactly right in my comment. The behavior you're seeing is perfectly permissible.
You can force what you want using the launch policy like so:
std::future<int> the_answer=std::async(std::launch::async,calculate_the_answer_to_LtUaE);
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