c++多线程并行计算

2021/5/15 14:55:22

本文主要是介绍c++多线程并行计算,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

《C++并发编程实战》随笔

#include <iostream>
#include <algorithm>
#include <numeric>
#include <thread>
#include <vector>
#include <functional>
template<class Iterator,class T>
struct accumulate_block {
    void operator()(Iterator first,Iterator last,T &result) {
        result = std::accumulate(first,last,result);
    }
};

template<class Iterator,class T>
T parallel_accumulate(Iterator first,Iterator last,T init) {
    unsigned long const length = std::distance(first,last);
    if(!length)return init;
    // 假设最大线程为25
    unsigned long const min_pre_thread = 25;
    // 按照元素长度来分配线程,以免元素过少分配过量的线程
    unsigned long const max_threads = 
        (length + min_pre_thread) / min_pre_thread;
    unsigned long const hardware_threads = 
        std::thread::hardware_concurrency();
    //取本机可使用的最小执行线程
    unsigned long const num_threads = 
        std::min(hardware_threads != 0 ? hardware_threads : 2,max_threads);
    //计算每个线程需计算的量
    unsigned long const block_size = length / num_threads;
    std::vector<T> result(num_threads);
    std::vector<std::thread> threads(num_threads - 1);
    Iterator block_start = first;
    for(unsigned long i = 0;i < num_threads - 1;i ++) {
        Iterator block_end = block_start;
        std::advance(block_end,block_size);
        threads[i] = std::thread {
            accumulate_block<Iterator,T>(),
            block_start,
            block_end,
            std::ref(result[i])
        };
        block_start = block_end;
    };
    accumulate_block<Iterator,T>()(
        block_start,last,result[num_threads - 1]
    );
    for(auto &&th:threads)
        th.join();
    return std::accumulate(result.begin(),result.end(),init);
}

int main() {
    std::vector<int> ans {1,2,3,4,5};
    auto res = parallel_accumulate(ans.begin(),ans.end(),0);
    std::cout << res << "\n";
    return 0;
}

 



这篇关于c++多线程并行计算的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程