Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asynchronous function call C++0x

Tags:

c++

c++11

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.

like image 946
Steveng Avatar asked Dec 13 '10 05:12

Steveng


1 Answers

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);
like image 162
Omnifarious Avatar answered Sep 28 '22 09:09

Omnifarious