c++ 如何獲取多線程的返回值?(std::thread ,std::async)

//簡單的 c++11 線程,簡單方便,成員函數隨便調用,非成員函數也同樣,如須要獲取返回時,請自行使用條件變量 std::thread run([&](){ //執行一些耗時的操做 return 0; }); run.detach();
auto run=std::async([&](){ return this->執行一些耗時的操做成員函數(); }); run.get();
auto run=std::async(std::launch::async,[&](){ return this->執行一些耗時的操做成員函數(); }); run.get();
auto future = std::async(std::launch::deferred, function, arg1, arg2); // some time later, possibly in another thread: future.get(); // calls the function with the arguments
// Console.cpp : 定義控制檯應用程序的入口點。 // #include "stdafx.h" #include <stdlib.h> #include <iostream> #include <thread> //線程庫 #include <future> #include <mutex> #include<numeric> std::mutex g_display_mutex; void foo() { std::thread::id this_id = std::this_thread::get_id(); g_display_mutex.lock(); std::cout << "thread " << this_id << " sleeping...\n"; g_display_mutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(0)); } void threadTest() { std::thread t1(foo); std::thread t2(foo); t1.join(); t2.join(); } int sum(int &x, int &y) { std::cout << std::hex << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); return x + y; } int sums(int x, int y,int z) { std::cout << std::hex << std::this_thread::get_id() << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); return x + y + z; } int main() { int x = 3; int y = 4; std::future<int> fu = std::async(sums, 3, 4,5); //std::future<int> fu = std::async(sum,std::ref(x),std::ref(y)); std::cout << fu.get() << std::endl; //獲取當前計算機線程數量 std::cout << std::thread::hardware_concurrency() << std::endl; //獲取當前線程ID std::cout << std::hex <<std::this_thread::get_id() << std::endl; system("pause"); return 0; } 
相關文章
相關標籤/搜索