【发布时间】:2019-09-06 06:31:14
【问题描述】:
让我们说一个函数,
int fun(){
static int a = 10;
a = a+1;
return a;
}
上面的函数返回一个整数值,
//Without thread obtaining return value
#include<iostream>
int main()
{
int var = 0;
var = fun();
std::cout << "The value " << value << std::endl;
return 0;
}
现在有什么方法可以在C++11线程调用时获取返回值,
//Using thread
#include<iostream>
#include<thread>
int main()
{
std::thread t1(fun);//Invoking thread
//How to obtain the return value of the thread ?
return 0;
}
谢谢!
【问题讨论】:
-
int return_of_t1; std::thread t1([&return_of_t1]{return_of_t1 = fun();}); -
顺便说一句,从不同线程调用
fun会导致最终混乱。 -
好的,我们可以使用 lambda 函数,我想我们可以通过使用锁定机制来避免混乱。
-
std::async被设计用来做这样的工作。
标签: c++ multithreading c++11