// // Created by light on 19-11-5. // #include #include #include #include #include using namespace std; //使得每个线程具有最小数目的元素以避免过多的线程开销 template struct accumulate_block { void operator()(Iterator first, Iterator last, T &result) { result = std::accumulate(first, last, result); } }; template T parallel_accumlate(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; cout< results(num_threads); std::vector 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(), block_start, block_end, std::ref(results[i])); block_start = block_end; } accumulate_block()(block_start, last, results[num_threads - 1]); std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); return std::accumulate(results.begin(), results.end(), init); } int main() { vector v{3,4,5,6}; int res=0; cout<