asynchronous function call C++0x
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-pr开发者_如何转开发omises.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);
"The default launch policy for std::async is std::launch::any, which means that the implementation gets to 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 make sure that the async call gets placed in a new thread. Otherwise it may just put off calling the calculation function until the_answer.get()
and invoke it in the current thread.
精彩评论