THM1176InstrumentManager  1.0
Qt Object abstraction for Metrolab THM1176
Synchronization.h
Go to the documentation of this file.
1 
5 #pragma once
6 
7 #include <mutex>
8 #include <thread>
9 #include <condition_variable>
10 
11 namespace MTL {
12  namespace Synchronization {
13 
14  //----------------------------------------------------------------------//
16  typedef std::mutex CMutex;
17 
18  //----------------------------------------------------------------------//
20  typedef std::recursive_mutex CRecursiveMutex;
21 
22  //----------------------------------------------------------------------//
24  class CSemaphore
25  {
26  private:
27  std::mutex m_mutex;
28  std::condition_variable m_condition;
29  unsigned long m_count = 0; // Initialized as locked.
30 
31  public:
33  void notify() {
34  std::unique_lock<decltype(m_mutex)> lock(m_mutex);
35  ++m_count;
36  m_condition.notify_one();
37  }
38 
40  void wait() {
41  std::unique_lock<decltype(m_mutex)> lock(m_mutex);
42  while (!m_count) // Handle spurious wake-ups.
43  m_condition.wait(lock);
44  --m_count;
45  }
46 
48  bool try_wait() {
49  std::unique_lock<decltype(m_mutex)> lock(m_mutex);
50  if (m_count) {
51  --m_count;
52  return true;
53  }
54  return false;
55  }
56  };
57 
58  //----------------------------------------------------------------------//
61  template <typename LockType>
62  class CLockGuard
63  {
64  private:
65  LockType & m_rLock;
66  public:
69  CLockGuard(LockType & rLock)
70  : m_rLock(rLock)
71  {
72  m_rLock.lock();
73  }
74 
76  virtual ~CLockGuard()
77  {
78  m_rLock.unlock();
79  }
80  };
81 
82  //----------------------------------------------------------------------//
84  typedef std::thread CThread;
85 
86  } // namespace Synchronization
87 } // namespace MTL
MTL::Synchronization::CSemaphore::notify
void notify()
Raise a semaphore.
Definition: Synchronization.h:33
MTL::Synchronization::CSemaphore
Counting semaphore.
Definition: Synchronization.h:25
MTL::Synchronization::CMutex
std::mutex CMutex
Mutex.
Definition: Synchronization.h:16
MTL
Definition: CTHM1176InstrumentManager.h:179
MTL::Synchronization::CLockGuard::CLockGuard
CLockGuard(LockType &rLock)
Constructor.
Definition: Synchronization.h:69
MTL::Synchronization::CSemaphore::try_wait
bool try_wait()
Check whether a semaphore has been raised.
Definition: Synchronization.h:48
MTL::Synchronization::CLockGuard::~CLockGuard
virtual ~CLockGuard()
Destructor.
Definition: Synchronization.h:76
MTL::Synchronization::CThread
std::thread CThread
Thread.
Definition: Synchronization.h:84
MTL::Synchronization::CSemaphore::wait
void wait()
Wait for a semaphore.
Definition: Synchronization.h:40
MTL::Synchronization::CLockGuard
Lock.
Definition: Synchronization.h:63
MTL::Synchronization::CRecursiveMutex
std::recursive_mutex CRecursiveMutex
Recursive Mutex.
Definition: Synchronization.h:20