gpt4 book ai didi

c++ - 异步函数调用 C++0x

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:48 26 4
gpt4 key购买 nike

我正在使用来自 http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-8-futures-and-promises.html 的代码测试 std::async 函数

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() 用于等待函数完成并检索结果。

谢谢。

最佳答案

如果您阅读链接到的有关“启动政策”的部分,您会发现我的评论完全正确。您看到的行为是完全允许的。

您可以像这样使用启动策略强制执行您想要的操作:

std::future<int> the_answer=std::async(std::launch::async,calculate_the_answer_to_LtUaE);

关于c++ - 异步函数调用 C++0x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4426141/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com