std::accumulate异常安全的两个并行版本

来源:互联网 发布:平民护肤品推荐 知乎 编辑:程序博客网 时间:2024/05/16 18:11

为了避免异常发生而导致的内存泄漏通常有两种方法解决:

1、采用try 和catch

2、在一个对象的析构函数中检测,线程是否join。(毕竟这是C++中惯用的清除资源方法)

本文主要实现第二种:

class join_threads{std::vector<std::thread>& threads;public:explicit join_threads(std::vector<std::thread>& threads_): threads(threads_){}~join_threads(){for (unsigned long i = 0; i < threads.size(); ++i){if (threads[i].joinable())threads[i].join();}}};

采用std::future和std::promise实现的std::accumulate异常安全并行版本:

template<typename Iterator,typename T>struct accumulate_block{    T operator()(Iterator first,Iterator last)    {        return std::accumulate(first,last,T());    }};template<typename Iterator,typename T>T parallel_accumulate(Iterator first,Iterator last,T init){    unsigned long const length=std::distance(first,last);    if(!length)        return init;    unsigned long const min_per_thread=25;    unsigned long const max_threads=        (length+min_per_thread-1)/min_per_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<std::future<T> > futures(num_threads-1);    std::vector<std::thread> threads(num_threads-1);    join_threads joiner(threads);    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);        std::packaged_task<T(Iterator,Iterator)> task(            accumulate_block<Iterator,T>());        futures[i]=task.get_future();        threads[i]=std::thread(std::move(task),block_start,block_end);        block_start=block_end;    }    T last_result=accumulate_block()(block_start,last);    T result=init;    for(unsigned long i=0;i<(num_threads-1);++i)    {        result+=futures[i].get();    }    result += last_result;    return result;}

使用std::async实现的std::accumulate异常安全并行版本:


template<typename Iterator,typename T>T parallel_accumulate(Iterator first,Iterator last,T init){    unsigned long const length=std::distance(first,last);    unsigned long const max_chunk_size=25;    if(length<=max_chunk_size)    {        return std::accumulate(first,last,init);    }    else    {        Iterator mid_point=first;        std::advance(mid_point,length/2);        std::future<T> first_half_result=            std::async(parallel_accumulate<Iterator,T>,                       first,mid_point,init);        T second_half_result=parallel_accumulate(mid_point,last,T());        return first_half_result.get()+second_half_result;    }}


0 0