首页 > 解决方案 > 从线程运行函数时如何返回值

问题描述

使用 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

标签: c++multithreading

解决方案


您不能使用函数从函数返回值,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; 
}

推荐阅读