lokinet/llarp/util/thread/barrier.hpp
Jason Rhinelander e470a6d73e C++17 niceties
- class template argument deduction lets us write `std::unique_lock
  foo{mutex}` instead of `std::unique_lock<mutex_type> foo{mutex}` which
  makes the `unique_lock` and `shared_lock` functions unnecessary.

- Replace GNU-specific warn_unused_result attribute with C++17-standard
  [[nodiscard]]

- Remove pre-C++17 workaround code for fold expressions, void_t
2020-05-12 16:42:35 -03:00

47 lines
1.0 KiB
C++

#pragma once
#include <mutex>
#include <condition_variable>
namespace llarp
{
namespace util
{
/// Barrier class that blocks all threads until the high water mark of
/// threads (set during construction) is reached, then releases them all.
class Barrier
{
std::mutex mutex;
std::condition_variable cv;
unsigned pending;
public:
Barrier(unsigned threads) : pending{threads}
{
}
/// Returns true if *this* Block call is the one that releases all of
/// them; returns false (i.e. after unblocking) if some other thread
/// triggered the released.
bool
Block()
{
std::unique_lock lock{mutex};
if (pending == 1)
{
pending = 0;
lock.unlock();
cv.notify_all();
return true;
}
else if (pending > 1)
{
pending--;
}
cv.wait(lock, [this] { return !pending; });
return false;
}
};
} // namespace util
} // namespace llarp