1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <string>
#include <future>
#include <mutex>
#include <algorithm>
#include <vector>
#include <numeric>
#include <atomic>
template < typename RA_ITERATOR, typename FN >
void parallel_for( RA_ITERATOR begin, RA_ITERATOR end, FN fn, std::size_t seg_size = 1024*128 )
{
const std::size_t n = end - begin ;
#ifndef NDEBUG
{
static std::mutex lock ;
std::lock_guard<std::mutex> guard(lock) ;
std::cout << "parallel_for: n == " << n << " thread: " << std::this_thread::get_id() << '\n' ;
}
#endif // NDEBUG
if( n < seg_size ) std::for_each( begin, end, fn ) ;
else
{
auto future = std::async( std::launch::async, parallel_for<RA_ITERATOR,FN>, begin, begin+n/2, fn, seg_size ) ;
parallel_for( begin+n/2, end, fn, seg_size ) ;
future.wait() ;
}
}
int main ()
{
const long long N = 1'000'000 ;
std::vector<int> vec(N) ;
std::iota( vec.begin(), vec.end(), 1 ) ;
std::atomic<long long> sum{0} ;
parallel_for( vec.begin(), vec.end(), [&sum]( int& v ) { v += 2 ; sum += v ; } ) ;
std::cout << sum << '\n'
<< N * (N+1)/2 + N*2 << '\n' ; // should be equal to sum
}
|