【问题标题】:How would I return a value while running a function from a thread [duplicate]从线程运行函数时如何返回值[重复]
【发布时间】:2020-09-25 01:08:47
【问题描述】:

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


【解决方案1】:

您不能使用 std::thread 从函数中返回值,但您可以更改 std::thread 的结构以获取您的值或使用 std::sync 返回一个包含您的值的 std::future&lt;T&gt;,如下所示

#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; 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2016-01-09
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多