异步函数调用C ++ 0x [英] asynchronous function call C++0x

查看:111
本文介绍了异步函数调用C ++ 0x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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()并获取打印在屏幕。如果我注释掉the_answer.get()行,我不会得到任何打印。这是std :: async函数的预期行为还是我在这里做错了?这是因为我认为the_answer.get()用于等待函数完成和检索结果。

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.

感谢。

推荐答案

你链接到关于启动政策,你会看到,我完全正确的在我的评论。

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);

这篇关于异步函数调用C ++ 0x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆