gpt4 book ai didi

c++ - c++同时调用多个函数返回值

转载 作者:行者123 更新时间:2023-11-28 00:14:57 25 4
gpt4 key购买 nike

我是 C/C++ 的新手。我正在尝试使用返回值同时调用 2 个函数。我做了一些研究,我开始知道线程不适合这个,因为很难通过线程获得返回值。我为此使用了带有异步的 future 库,但它没有一次调用多个函数(我已经用 sleep() 测试了它,我看到它等待其他函数完成以获取返回值)。请查找代码在这里,有人可以通过显示一个简单的代码作为示例来帮助我吗?

#include <iostream>      
#include <future>
#include <windows.h>
#include <string>
using namespace std;

// a non-optimized way of checking for prime numbers:
string test(string t1)
{
string h = "Hello";
string hh = h+t1;
return hh;
}
string test1(string t2)
{
string hh = "Hello";
string hhh = hh+t2;
return hhh;
}
int main ()
{
string t1 = "Hai test1";
string t2 = "Hai teset2";
future<string> stt = async (test,t1);
future<string> sttt = async (test1,t2);

string re1 = stt.get();
string re2 = sttt.get();
cout << re1 << endl;
cout << re2 << endl;

return 0;
}

最佳答案

您应该已经查阅了一些标准库引用资料: http://en.cppreference.com/w/cpp/thread/async

如您所见,std::async 有一个重载,它采用额外的启动策略。您调用的 std::async 存在以下问题:

Behaves the same as async(std::launch::async | std::launch::deferred, f, args...). In other words, f may be executed in another thread or it may be run synchronously when the resulting std::future is queried for a value.

If both the std::launch::async and std::launch::deferred flags are set in policy, it is up to the implementation whether to perform asynchronous execution or lazy evaluation.

所以最后它取决于你的编译器会发生什么。解决方案非常简单:

    future<string> stt = async (launch::async,test,t1);
future<string> sttt = async (launch::async,test1,t2);

string re1 = stt.get();
string re2 = sttt.get();

关于c++ - c++同时调用多个函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30916130/

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