c++ - 从线程运行函数时如何返回值
问题描述
使用 std #include 如果我想要一个线程运行它,我将如何返回一个值?
例如
include <iostream>
#include <thread>
usingnamespace std;
int func(int a)
{
int b = a*a
return b;
}
int main()
{
thread t(func);
t.join();
return 0;
}
我将如何修改
thread t(func);
这样我就可以得到 b
解决方案
您不能使用函数从函数返回值,std::thread
但您可以更改 的结构std::thread
以获取您的值或使用std::sync
它返回std::future<T>
持有您的值,如下所示
#include <iostream>
#include <thread>
int func(int a)
{
int b = a * a;
return b;
}
int main()
{
int result;
std::thread t([&] { result = func(3); });
t.join();
std::cout << result;
return 0;
}
或者
#include <iostream>
#include <future>
int main()
{
auto f = std::async(std::launch::async, func, 3);
std::cout << f.get();
return 0;
}
推荐阅读
- regex-group - 正则表达式如何从多行中获取 3 组行
- angular - 如何使用 eventemitter 检查输入的当前值?
- microsoft-graph-api - 在 Microsoft Graph API 中处理用户特定的共享日历 ID
- python - 使用 pandas 在一天内获取 10 分钟的索引
- vb.net - 无法分配角色 discord.net
- lua - 我在“...”附近收到错误意外符号错误我已将其范围缩小到这里的某个地方
- terminal - 终端:如何从硬盘驱动器上永久删除文件
- ruby-on-rails - 如何使用 docker & ansible ROR 部署和运行捆绑安装?
- kotlin - 在 Kotlin 中,var s: String = "hello" 和 var s = "hello" as String 有什么区别?
- bash - 在 Bash 脚本中并行使用 Ping