Semaphore.hpp
Go to the documentation of this file.
1 // @formatter:off
2 //
3 // Balau core C++ library
4 //
5 // Copyright (C) 2008 Bora Software (contact@borasoftware.com)
6 //
7 // Licensed under the Boost Software License - Version 1.0 - August 17th, 2003.
8 // See the LICENSE file for the full license text.
9 //
10 
16 
17 #ifndef COM_BORA_SOFTWARE__BALAU_CONCURRENT__SEMAPHORE
18 #define COM_BORA_SOFTWARE__BALAU_CONCURRENT__SEMAPHORE
19 
20 #include <condition_variable>
21 
22 namespace Balau::Concurrent {
23 
27 class Semaphore {
31  public: explicit Semaphore(unsigned int count_ = 0) : count(count_) {}
32 
36  public: void increment() {
37  std::lock_guard<std::mutex> lock(mutex);
38  ++count;
39  conditionVariable.notify_one();
40  }
41 
45  public: void decrement() {
46  std::unique_lock<std::mutex> lock(mutex);
47 
48  while (count == 0) {
49  conditionVariable.wait(lock);
50  }
51 
52  --count;
53  }
54 
56 
57  private: std::mutex mutex;
58  private: std::condition_variable conditionVariable;
59  private: unsigned int count;
60 };
61 
62 } // namespace Balau::Concurrent
63 
64 #endif // COM_BORA_SOFTWARE__BALAU_CONCURRENT__SEMAPHORE
void increment()
Increment the semaphore.
Definition: Semaphore.hpp:36
Traditional semaphore synchronisation object.
Definition: Semaphore.hpp:27
Concurrency control classes.
Definition: CyclicBarrier.hpp:26
Semaphore(unsigned int count_=0)
Create a semaphore object, setting an initial count if desired.
Definition: Semaphore.hpp:31
void decrement()
Decrement the semaphore, blocking if the count is zero.
Definition: Semaphore.hpp:45