GrPPI  0.2
Generic and Reusable Parallel Pattern Interface
native/reduce.h
Go to the documentation of this file.
1 
21 #ifndef GRPPI_NATIVE_REDUCE_H
22 #define GRPPI_NATIVE_REDUCE_H
23 
25 
26 #include <thread>
27 
28 namespace grppi {
29 
50 template < typename InputIt, typename Identity, typename Combiner>
52  InputIt first, InputIt last,
53  Identity identity,
54  Combiner && combine_op)
55 {
56  auto identityVal = identity;
57 
58  int numElements = last - first;
59  int elemperthr = numElements/ex.concurrency_degree();
60  std::atomic<int> finishedTask(1);
61  //local output
62  std::vector<typename std::iterator_traits<InputIt>::value_type> out(ex.concurrency_degree());
63  //Create threads
64  for(int i=1;i<ex.concurrency_degree();i++){
65  auto begin = first + (elemperthr * i);
66  auto end = first + (elemperthr * (i+1));
67  if(i == ex.concurrency_degree() -1) end = last;
68  ex.pool.create_task(boost::bind<void>(
69  [&](InputIt begin, InputIt end, int tid){
70  out[tid] = identityVal;
71  for( ; begin != end; begin++ ) {
72  out[tid] = combine_op(out[tid], *begin );
73  }
74  finishedTask++;
75  },
76  std::move(begin), std::move(end), i
77  ));
78  }
79  //Main thread
80  auto end = first + elemperthr;
81  out[0] = identityVal;
82  for(;first!=end;first++){
83  out[0] = combine_op( out[0], *first);
84  }
85 
86  while(finishedTask.load()!=ex.concurrency_degree());
87 
88  auto outVal = out[0];
89  for(unsigned int i = 1; i < out.size(); i++){
90  outVal = combine_op(outVal, out[i]);
91  }
92  return outVal;
93 }
94 
100 }
101 #endif
Definition: callable_traits.h:24
int concurrency_degree() const noexcept
Get number of grppi trheads.
Definition: parallel_execution_native.h:178
void create_task(T task)
Definition: pool.h:43
thread_pool pool
Thread pool for lanching workers.
Definition: parallel_execution_native.h:235
Native parallel execution policy. This policy uses ISO C++ threads as implementation building block a...
Definition: parallel_execution_native.h:136
auto reduce(parallel_execution_native &ex, InputIt first, InputIt last, Identity identity, Combiner &&combine_op)
Invoke Reduce pattern with identity value on a data sequence with parallel native execution...
Definition: native/reduce.h:51