我正在使用以下代码测试 std::async 函数http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-8-futures-and-promises.html 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);
我需要调用 the_answer.get() 来调用calculate_the_answer_to_LtUaE() 并将 Aaa 打印在屏幕上。如果我注释掉 the_answer.get() 行,我将不会打印任何内容。这是 std::async 函数的预期行为还是我在这里做错了什么?这是因为我认为 the_answer.get() 用于等待函数完成并检索结果。
Thanks.
如果您阅读了链接到的有关“启动政策”的部分,您会发现我的评论完全正确。您所看到的行为是完全可以允许的。
您可以使用启动策略强制执行您想要的操作,如下所示:
std::future<int> the_answer=std::async(std::launch::async,calculate_the_answer_to_LtUaE);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)