Taskflow  3.2.0-Master-Branch
Loading...
Searching...
No Matches
semaphore.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <vector>
4#include <mutex>
5
6#include "declarations.hpp"
7
13namespace tf {
14
15// ----------------------------------------------------------------------------
16// Semaphore
17// ----------------------------------------------------------------------------
18
68class Semaphore {
69
70 friend class Node;
71
72 public:
73
84 explicit Semaphore(size_t max_workers);
85
89 size_t count() const;
90
91 private:
92
93 std::mutex _mtx;
94
95 size_t _counter;
96
97 std::vector<Node*> _waiters;
98
99 bool _try_acquire_or_wait(Node*);
100
101 std::vector<Node*> _release();
102};
103
104inline Semaphore::Semaphore(size_t max_workers) :
105 _counter(max_workers) {
106}
107
108inline bool Semaphore::_try_acquire_or_wait(Node* me) {
110 if(_counter > 0) {
111 --_counter;
112 return true;
113 }
114 else {
115 _waiters.push_back(me);
116 return false;
117 }
118}
119
120inline std::vector<Node*> Semaphore::_release() {
122 ++_counter;
123 std::vector<Node*> r{std::move(_waiters)};
124 return r;
125}
126
127inline size_t Semaphore::count() const {
128 return _counter;
129}
130
131} // end of namespace tf. ---------------------------------------------------
132
class to create a semophore object for building a concurrency constraint
Definition semaphore.hpp:68
Semaphore(size_t max_workers)
constructs a semaphore with the given counter
Definition semaphore.hpp:104
size_t count() const
queries the counter value (not thread-safe during the run)
Definition semaphore.hpp:127
T lock(T... args)
T move(T... args)
taskflow namespace
Definition small_vector.hpp:27