37.并行计算汇总

 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 }

 

posted @ 2018-03-12 15:23  喵小喵~  阅读(147)  评论(0编辑  收藏  举报