libcoro  1.0
Coroutine support library for C++20
semaphore.h
1 #pragma once
2 #include "future.h"
3 
4 #include <mutex>
5 #include <queue>
6 
7 namespace coro {
8 
10 
14 class semaphore {
15 public:
16 
18 
21  semaphore() = default;
22  semaphore(unsigned long counter): _counter (counter) {}
23 
25 
33  return [&](auto promise) {
34  std::lock_guard _(_mx);
35  if (_counter) {
36  --_counter;
37  promise();
38  } else {
39  _waiting.push(std::move(promise));
40  }
41  };
42  }
43 
45 
48  coro::future<void> operator co_await() {
49  return acquire();
50  }
51 
53 
61  std::lock_guard _(_mx);
62  if (_waiting.empty()) {
63  ++_counter;
64  } else {
65  r = _waiting.front()();
66  _waiting.pop();
67  }
68  return r;
69  }
70 
71 
73 
79  long get() {
80  std::lock_guard _(_mx);
81  if (_counter) return static_cast<long>(_counter);
82  return -static_cast<long>(_waiting.size());
83  }
84 
85 
87 
91  bool try_acquire() {
92  std::lock_guard _(_mx);
93  if (!_counter) return false;
94  --_counter;
95  return true;
96  }
97 
98 
99 protected:
100  unsigned long _counter = 0;
101  std::mutex _mx;
102  std::queue<coro::promise<void> > _waiting;
103 
104 };
105 
106 
107 }
contain notification to be delivered to the asociated future
Definition: future.h:91
Carries reference to future<T>, callable, sets value of an associated future<T>
Definition: future.h:73
semaphore()=default
construct semaphore with counter set to zero
bool try_acquire()
Try acquire the semaphore.
Definition: semaphore.h:91
coro::future< void > acquire()
acquire the semaphore
Definition: semaphore.h:32
coro::promise< void >::notify release()
Release the semaphore.
Definition: semaphore.h:59
long get()
Retrieve counter.
Definition: semaphore.h:79
Implements semaphore for coroutines.
Definition: semaphore.h:14
main namespace
Definition: aggregator.h:8