Skip to content

Commit

Permalink
Add barrier concept to autowiring::parallel
Browse files Browse the repository at this point in the history
There are cases, especially when dealing with lambdas that do not return anything, where the user doesn't care to iterate over each available item and just wants to return when everything currently outstanding is completed.
  • Loading branch information
codemercenary committed Oct 15, 2015
1 parent b05b8d3 commit 5435dd9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
12 changes: 12 additions & 0 deletions autowiring/Parallel.h
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,17 @@ class parallel {
return parallel_collection<T> { begin<T>(), end<T>() };
}

// Blocks until all outstanding work is done
void barrier(void) {
std::unique_lock<std::mutex> lk(m_queueMutex);
m_queueUpdated.wait(lk, [this] {
size_t totalReady = m_nVoidEntries;
for (auto& entry : m_queue)
totalReady += entry.second.size();
return m_outstandingCount == totalReady;
});
}

// Get an iterator to the begining of out queue of job results
template<typename T>
parallel_iterator<T> begin(void) {
Expand Down Expand Up @@ -210,6 +221,7 @@ class parallel {
// For void entries we don't need a queue, we can just keep a general count of "done"
size_t m_nVoidEntries = 0;

// Total number of entries currently outstanding:
size_t m_outstandingCount = 0;

AutoCurrentContext m_ctxt;
Expand Down
12 changes: 12 additions & 0 deletions src/autowiring/test/ParallelTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,15 @@ TEST_F(ParallelTest, VoidReturnAll) {
ASSERT_EQ(100UL, i) << "A sufficient number of empty lambdas were not encountered";
ASSERT_EQ(100, *val) << "Not all pended lambda functions were called as expected";
}

TEST_F(ParallelTest, Barrier) {
AutoCurrentContext()->Initiate();
autowiring::parallel p;

std::atomic<size_t> x{ 0 };
for (size_t i = 0; i < 1000; i++)
p += [&x] { x++; };

p.barrier();
ASSERT_EQ(1000, x) << "Not all parallel watchers were completed on return from join";
}

0 comments on commit 5435dd9

Please sign in to comment.