CPP多线程实现并行计算

#include #include #include #include #include #include #include using namespace std; #define COUNT 5000000 long longadd(vector *arr, long longstart, long long count) { static mutex m; //仅仅初始化一次 int sum(0); //保存结果 for (long long i = 0; i < count; i++) { sum += (*arr)[start+i]; //根据下标累加 } { lock_guardlckg(m); //锁定 cout <<"线程ID:"<< this_thread::get_id() <<" count="<>abc ; vector>result; //实现并行计算 获取CPU核心个数创建线程必须为CPU核心的个数 long longcpus = thread::hardware_concurrency(); cout << "cpu核心个数:" << cpus << endl; //启动线程存储结果使用线程分块 for (long long i = 0; i < cpus * 2; i++) { ////线程切割线程分块 long longbatch_each = COUNT / (cpus * 2); if (i == cpus * 2-1) { batch_each = COUNT - COUNT / (cpus * 2)*i; //让最后一个线程承载多点 } result.push_back(async(add,&myint,i*batch_each,batch_each)); //压入数据 } //分数据 long longlastresult(0); //最终结果 //汇总数据 for (long long i = 0; i < cpus * 2; i++) { lastresult += result[i].get(); //累加 } cout << "lastresult ="<< lastresult << endl; cin.get(); }

CPP多线程实现并行计算
文章图片

    推荐阅读