1. 程式人生 > >37.並行計算匯總

37.並行計算匯總

guard arr 互斥 pan nbsp res read div size

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <iostream>
 3 #include <thread>
 4 #include <future>
 5 #include <vector>
 6 #include <cstdlib>
 7 #include <mutex>
 8 using namespace std;
 9 #define COUNT 1000000
10 
11 //創建互斥量
12 mutex m;
13 
14 //多線程計算加法
15 int add(vector<int
> *arr,int start,int count) 16 { 17 static mutex m;//只會初始化一次 18 int sum(0);//保存結果 19 for (int i = 0; i < count; i++) 20 { 21 sum += (*arr)[start + i]; 22 } 23 { 24 //鎖定,離開作用區域,自動釋放 25 lock_guard<mutex> lckg(m); 26 cout << "thread=" << this_thread::get_id()
27 << ",count=" << count 28 << ",sum=" << sum << endl; 29 } 30 return sum; 31 } 32 33 void main() 34 { 35 vector <int>data(COUNT);//數組,100萬個數據 36 for (int i = 0; i < COUNT; i++) 37 { 38 data[i] = (i + 1) % 1000;// 賦值初始化
39 } 40 41 vector<future<int>> result;//結果數組,存放結果 42 43 int cpus = thread::hardware_concurrency();//CPU核心的個數 44 45 for (int i = 0; i < cpus * 2; i++) 46 { 47 int batch_each = COUNT / (cpus * 2); 48 //最後一個線程所計算的個數 49 if (i == (cpus * 2) - 1) 50 { 51 batch_each = COUNT - COUNT / (cpus * 2)*i; 52 } 53 //不斷壓入結果 54 result.push_back(async(add, &data, i*batch_each, batch_each)); 55 //async直接返回future類型結果 56 } 57 58 //匯總 59 int lastresult(0); 60 for (int i = 0;i<result.size();i++) 61 { 62 lastresult += result[i].get();//匯總結果 63 } 64 cout << "結果=" << lastresult << endl; 65 66 cin.get(); 67 }

37.並行計算匯總