异步函数调用C++ 0x

Ste*_*eng 6 c++ c++11

我正在测试std :: async函数,代码来自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);
Run Code Online (Sandbox Code Playgroud)

我需要调用the_answer.get()来调用calculate_the_answer_to_LtUaE()并在屏幕上打印Aaa.如果我注释掉了the_answer.get()行,我就不会打印任何内容.这是std :: async函数的预期行为还是我在这里做错了什么?这是因为我认为the_answer.get()用于等待函数完成并检索结果.

谢谢.

Omn*_*ous 5

如果您阅读了与"发布政策"相关联的内容,您会发现我的评论完全正确.你所看到的行为是完全允许的.

您可以使用启动策略强制执行所需的操作,如下所示:

std::future<int> the_answer=std::async(std::launch::async,calculate_the_answer_to_LtUaE);
Run Code Online (Sandbox Code Playgroud)