C ++ async function call 0x

I am testing a std :: async function with 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 call calculate_the_answer_to_LtUaE () and get the Aaa printed on the screen. If I commented on the_answer.get () line, I would not print anything. Is this the intended behavior of the std :: async function, or am I doing something wrong here? This is because I thought the_answer.get () was used to wait for the function to complete and to get the result.

Thanks.

+6
c ++ c ++ 11
source share
2 answers

If you read the section related to “startup policies”, you will see that I am right in your comment. The behavior you see is perfectly acceptable.

You can force what you want using the launch policy as follows:

 std::future<int> the_answer=std::async(std::launch::async,calculate_the_answer_to_LtUaE); 
+5
source share

"The default startup policy for std :: async is std :: launch :: any, which means that the implementation can choose for you."

You need std::launch::async , basically:

 std::future<int> the_answer=std::async(std::launch::async, calculate_the_answer_to_LtUaE); // ^^^^^^^^^^^^^^^^^^ 

To verify that the asynchronous call is placed on a new thread. Otherwise, it can simply disable the call to the calculation function before the_answer.get() and call it in the current thread.

+4
source share

All Articles