gpt4 book ai didi

c++ - 如何从std::thread返回值

转载 作者:行者123 更新时间:2023-12-02 10:29:49 25 4
gpt4 key购买 nike

我有返回值的函数。我想将线程用于doSth函数,并为上述变量设置返回值,这是一个示例:

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// func for execution
int doSth(int number)
{
return number;
}

int main()
{
// some code ...
int numberOne; // no value now, but in thread I want to set a value from it
int numberTwo; // depending on function input value
thread t1(doSth, 1); // set numberOne = 1;
thread t2(doSth, 2); // set numberTwo = 2;
// wait them to execute
t1.join();
t2.join();
// now I should have numberOne = 1; numberTwo = 2
// some code ...
return 0;
}
我该怎么办?

最佳答案

How to return value from std::thread


除了其他答案中显示的 std::async之外,您还可以使用 std::packaged_task:
std::packaged_task<int(int)> task{doSth};
std::future<int> result = task.get_future();
task(1);
int numberOne = result.get();
这允许分离任务的创建,并在需要时执行它。

关于c++ - 如何从std::thread返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62697646/

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