1. 程式人生 > >2.任務包多線程並行計算

2.任務包多線程並行計算

線程 task promise sin res mutex AC his mut

 1 #include <future>//進程通信,獲取未來的結果
 2 #include<iostream>
 3 #include <thread>
 4 #include <string>
 5 #include <chrono>//時間
 6 #include <mutex>//互斥量
 7 using namespace std;
 8 
 9 //創建互斥量
10 mutex m;
11 
12 //全局通信變量
13 promise<string> val;
14 
15 void main()
16 {
17     //
訪問外部變量[=] 18 auto fun = [=](int index)->int 19 { 20 //加鎖 21 lock_guard<mutex> lckg(m); 22 23 //顯示線程id 24 cout << "線程編號:" << this_thread::get_id() << " " << index << endl; 25 //等待十秒 26 this_thread::sleep_for(chrono::seconds(1
)); 27 28 //計算 29 return index * 1024; 30 }; 31 32 //獲取返回值,創建任務包 33 packaged_task<int(int)> pt1(fun); 34 packaged_task<int(int)> pt2(fun); 35 36 thread t1([&]() 37 { 38 pt1(23); 39 }); 40 thread t2([&]() 41 { 42 pt2(26
); 43 }); 44 45 //開啟線程,獲取結果,只能獲取一次 46 int res1 = pt1.get_future().get(); 47 int res2 = pt2.get_future().get(); 48 int last = res1 + res2; 49 cout << last << endl; 50 51 t1.joinable(); 52 t2.joinable(); 53 t1.join(); 54 t2.join(); 55 system("pause"); 56 }

2.任務包多線程並行計算