并行计算使用的是async, 通过每一个线程都进行相同的计算,最后在vector<future<int>>result; 将结果进行相加

全部代码

//
// Created by Administrator on 2021/6/29.
//
#include<iostream>
#include<thread>
#include<future>
#include<vector>
#include<cstdlib>


using namespace std;
#define COUNT 1000000

int add(vector<int>*arr, int start, int count)
{
    static mutex m; //只会初始化一次
    int sum(0); //保存结果的作用
    for(int i = 0; i < count; i++){
        sum += (*arr)[start + i];
    }
    {
        //显示结果必须, 仅仅计算多余, 加锁
        lock_guard<mutex> lck(m); //锁定
        cout << "thread" << this_thread::get_id << ",count" <<
        ",sum=" << sum << endl; //打印结果
    }
    return sum;
}


int main()
{
    vector<int>data(COUNT); //数组, 100万
    for(int i = 0; i < COUNT; i++)
    {
        data[i] = (i + 1) % 1000; //0-999
    }

    vector<future<int>>result; //结果数组
    int cpus = thread::hardware_concurrency(); //CPU核心的个数
    for(int i = 0; i < cpus * 2; i++)
    {
        int batch_each = COUNT / (cpus * 2); //
        if(i == (cpus * 2) - 1) {
            batch_each = COUNT - COUNT / (cpus * 2) * i; //最后一个承担更多的计算
        }
        //不断压入结果
        result.push_back(async(add, &data, i * batch_each, batch_each)); //返回结果
    }
    int lastresult(0);
    for(int i = 0; i < cpus * 2; i++)
    {
        lastresult += result[i].get();  //汇总结果
    }
    cout << "lastresult=" << lastresult << endl;
    cin.get();
}
//
// Created by Administrator on 2021/6/29.
//
#include<iostream>
#include<thread>
#include<future>
#include<vector>
#include<cstdlib>


using namespace std;
#define COUNT 1000000

int add(vector<int>*arr, int start, int count)
{
    static mutex m; //只会初始化一次
    int sum(0); //保存结果的作用
    for(int i = 0; i < count; i++){
        sum += (*arr)[start + i];
    }
    {
        //显示结果必须, 仅仅计算多余, 加锁
        lock_guard<mutex> lck(m); //锁定
        cout << "thread" << this_thread::get_id << ",count" <<
        ",sum=" << sum << endl; //打印结果
    }
    return sum;
}


int main()
{
    vector<int>data(COUNT); //数组, 100万
    for(int i = 0; i < COUNT; i++)
    {
        data[i] = (i + 1) % 1000; //0-999
    }

    vector<future<int>>result; //结果数组
    int cpus = thread::hardware_concurrency(); //CPU核心的个数
    for(int i = 0; i < cpus * 2; i++)
    {
        int batch_each = COUNT / (cpus * 2); //
        if(i == (cpus * 2) - 1) {
            batch_each = COUNT - COUNT / (cpus * 2) * i; //最后一个承担更多的计算
        }
        //不断压入结果
        result.push_back(async(add, &data, i * batch_each, batch_each)); //返回结果
    }
    int lastresult(0);
    for(int i = 0; i < cpus * 2; i++)
    {
        lastresult += result[i].get();  //汇总结果
    }
    cout << "lastresult=" << lastresult << endl;
    cin.get();
}

 

posted on 2021-06-29 01:48  python我的最爱  阅读(834)  评论(0编辑  收藏  举报