#ifndef AGGREGATING_BARRIER_HPP #define AGGREGATING_BARRIER_HPP #include #include #include template class AggregatingBarrier { public: typedef std::function AggregatingOperator; AggregatingBarrier(const AggregatingOperator& op, const T& startval, unsigned int nofthreads) : aggregating_operator(op), startval(startval), nofthreads(nofthreads), count(0), iterations(0) { } T wait(const T& val) { std::unique_lock lock(mutex); currentval = aggregating_operator(currentval, val); if (++count == nofthreads) { result = currentval; currentval = startval; count = 0; ++iterations; finished.notify_all(); } else { finished.wait(lock); } return result; } unsigned int get_iterations() const { return iterations; } private: std::mutex mutex; std::condition_variable finished; AggregatingOperator aggregating_operator; T startval; T currentval; T result; unsigned int nofthreads; unsigned int count; unsigned int iterations; }; #endif