Multithreading 如何使用c++;11多线程 #包括 #包括 使用名称空间std; int foo(int n){ int double n=n*2; 返回双工; } int main(){ int n=2; 螺纹t(foo,n); t、 join(); 返回0; }
就上述代码而言,我可以在主函数中获取doubleN的值吗?如何获取?您可以使用Multithreading 如何使用c++;11多线程 #包括 #包括 使用名称空间std; int foo(int n){ int double n=n*2; 返回双工; } int main(){ int n=2; 螺纹t(foo,n); t、 join(); 返回0; },multithreading,c++11,Multithreading,C++11,就上述代码而言,我可以在主函数中获取doubleN的值吗?如何获取?您可以使用std::promise和std::future,cppreferencestd::promise文档有一个示例演示如何使用promise在线程之间传输结果() #包括 #包括 #包括 使用名称空间std; intfoo(intn,std::promise double\u promise){ int double n=n*2; doubleN\u承诺。设置值(doubleN); 返回双工; } int main(){
std::promise
和std::future
,cppreferencestd::promise
文档有一个示例演示如何使用promise
在线程之间传输结果()
#包括
#包括
#包括
使用名称空间std;
intfoo(intn,std::promise double\u promise){
int double n=n*2;
doubleN\u承诺。设置值(doubleN);
返回双工;
}
int main(){
int n=2;
std::承诺与承诺;
std::future doubleN_future=doubleN_promise.get_future();
线程t(foo,n,std::move(double n_promise));
doubleN_future.wait();//等待doubleN
std::cout如果您想获得线程执行任务的结果,可以使用async
函数:
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int foo(int n, std::promise<int> doubleN_promise){
int doubleN = n * 2;
doubleN_promise.set_value(doubleN);
return doubleN;
}
int main(){
int n = 2;
std::promise<int> doubleN_promise;
std::future<int> doubleN_future = doubleN_promise.get_future();
thread t(foo, n, std::move(doubleN_promise));
doubleN_future.wait(); // wait for doubleN
std::cout << "doubleN=" << doubleN_future.get() << '\n';
t.join();
return 0;
}
intfoo(intn){
int double n=n*2;
返回双工;
}
int main(){
int n=2;
未来结果=异步(std::launch::async,foo,n);
库特
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int foo(int n, std::promise<int> doubleN_promise){
int doubleN = n * 2;
doubleN_promise.set_value(doubleN);
return doubleN;
}
int main(){
int n = 2;
std::promise<int> doubleN_promise;
std::future<int> doubleN_future = doubleN_promise.get_future();
thread t(foo, n, std::move(doubleN_promise));
doubleN_future.wait(); // wait for doubleN
std::cout << "doubleN=" << doubleN_future.get() << '\n';
t.join();
return 0;
}
int foo(int n){
int doubleN = n * 2;
return doubleN;
}
int main(){
int n = 2;
future<int> result = async(std::launch::async, foo,n);
cout << result.get() << endl; //4
return 0;
}