openMSX
Semaphore.hh
Go to the documentation of this file.
1 #ifndef SEMAPHORE_HH
2 #define SEMAPHORE_HH
3 
4 #include "noncopyable.hh"
5 #include <cassert>
6 #include <condition_variable>
7 #include <mutex>
8 
9 namespace openmsx {
10 
11 class Semaphore : private noncopyable
12 {
13 public:
14  explicit Semaphore(unsigned value);
15  void up();
16  void down();
17 
18 private:
19  std::mutex mutex;
20  std::condition_variable condition;
21  unsigned value;
22 };
23 
24 class ScopedLock : private noncopyable
25 {
26 public:
28  : lock(nullptr)
29  {
30  }
31 
32  explicit ScopedLock(Semaphore& lock_)
33  : lock(nullptr)
34  {
35  take(lock_);
36  }
37 
39  {
40  release();
41  }
42 
43  void take(Semaphore& lock_)
44  {
45  assert(!lock);
46  lock = &lock_;
47  lock->down();
48  }
49 
50  void release()
51  {
52  if (lock) {
53  lock->up();
54  lock = nullptr;
55  }
56  }
57 
58 private:
59  Semaphore* lock;
60 };
61 
62 } // namespace openmsx
63 
64 #endif
void take(Semaphore &lock_)
Definition: Semaphore.hh:43
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
Semaphore(unsigned value)
Definition: Semaphore.cc:5
ScopedLock(Semaphore &lock_)
Definition: Semaphore.hh:32
Based on boost::noncopyable, see boost documentation: http://www.boost.org/libs/utility.
Definition: noncopyable.hh:12