---
title: llarp/util/thread/barrier.hpp

---

# llarp/util/thread/barrier.hpp



## Namespaces

| Name           |
| -------------- |
| **[llarp](Namespaces/namespacellarp.md)** <br>[crypto.hpp] |
| **[llarp::util](Namespaces/namespacellarp_1_1util.md)**  |

## Classes

|                | Name           |
| -------------- | -------------- |
| class | **[llarp::util::Barrier](Classes/classllarp_1_1util_1_1Barrier.md)** <br>[Barrier]() class that blocks all threads until the high water mark of threads (set during construction) is reached, then releases them all.  |




## Source code

```cpp
#pragma once
#include <mutex>
#include <condition_variable>

namespace llarp
{
  namespace util
  {
    class Barrier
    {
      std::mutex mutex;
      std::condition_variable cv;
      unsigned pending;

     public:
      Barrier(unsigned threads) : pending{threads}
      {}

      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
```


-------------------------------

Updated on 2023-01-06 at 19:35:06 +0000
