Version: 1.0
semaphore.h
Go to the documentation of this file.
1 // Extrapolated from https://vorbrodt.blog/2019/02/05/fast-semaphore/
2 #pragma once
3 
4 #include <mutex>
5 #include <atomic>
6 #include <condition_variable>
7 #include <cassert>
8 
9 class semaphore
10 {
11 public:
12  semaphore(int count) noexcept
13  : m_count(count) {
14  assert(count > -1);
15  }
16 
17  void post() noexcept
18  {
19  {
20  std::unique_lock<std::mutex> lock(m_mutex);
21  ++m_count;
22  }
23  m_cv.notify_one();
24  }
25 
26  void wait() noexcept
27  {
28  std::unique_lock<std::mutex> lock(m_mutex);
29  m_cv.wait(lock, [&]() { return m_count != 0; });
30  --m_count;
31  }
32 
33 private:
34  int m_count;
35  std::mutex m_mutex;
36  std::condition_variable m_cv;
37 };
38 
40 {
41 public:
42  fast_semaphore(int count) noexcept
43  : m_count(count), m_semaphore(0) {}
44 
45  void post()
46  {
47  std::atomic_thread_fence(std::memory_order_release);
48  int count = m_count.fetch_add(1, std::memory_order_relaxed);
49  if (count < 0)
50  m_semaphore.post();
51  }
52 
53  void wait()
54  {
55  int count = m_count.fetch_sub(1, std::memory_order_relaxed);
56  if (count < 1)
57  m_semaphore.wait();
58  std::atomic_thread_fence(std::memory_order_acquire);
59  }
60 
61 private:
62  std::atomic<int> m_count;
63  semaphore m_semaphore;
64 };
void wait()
Definition: semaphore.h:53
fast_semaphore(int count) noexcept
Definition: semaphore.h:42
void post()
Definition: semaphore.h:45
void post() noexcept
Definition: semaphore.h:17
void wait() noexcept
Definition: semaphore.h:26
semaphore(int count) noexcept
Definition: semaphore.h:12