lokinet/llarp/util/thread/barrier.hpp
dr7ana 46ad8d4058 Clang format include sorting + CMake
- includes are now sorted in consistent, logical order; first step in an attempt to fix the tomfoolery (no relation to Tom) brought in by include-what-you-use
- shuffled around some cmake linking to simplify dependency graph
- superfluous files removed
2023-10-24 12:11:51 -07:00

46 lines
1.0 KiB
C++

#pragma once
#include <condition_variable>
#include <mutex>
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