libUTL++
Mutex.h
1 #pragma once
2 
4 
5 #include <libutl/host_thread.h>
6 #include <libutl/NamedObjectMI.h>
7 
9 
10 UTL_NS_BEGIN;
11 
13 // Mutex ///////////////////////////////////////////////////////////////////////////////////////////
15 
25 
27 class Mutex : public Object, public NamedObjectMI
28 {
29  friend class ConditionVar;
32 
33 public:
38  bool haveLock() const;
39 
44  bool trylock();
45 
47  void lock();
48 
50  void unlock();
51 
52 private:
53  void init();
54  void deInit();
55 
56 private:
57 #if UTL_HOST_OS == UTL_OS_MINGW
58  HANDLE _sem;
59  volatile long _count;
60 #else
61  pthread_mutex_t _mutex;
62 #endif
63  thread_handle_t _owner;
64  size_t _depth; // recursive locking depth
65 };
66 
68 // MutexGuard //////////////////////////////////////////////////////////////////////////////////////
70 
78 
81 {
82 public:
85  : _mutex(nullptr)
86  {
87  }
88 
93  MutexGuard(Mutex* mutex)
94  : _mutex(mutex)
95  {
96  ASSERTD(_mutex != nullptr);
97  _mutex->lock();
98  }
99 
102  {
103  unlock();
104  }
105 
110  void
111  lock(Mutex* mutex)
112  {
113  unlock();
114  ASSERTD(mutex != nullptr);
115  _mutex = mutex;
116  _mutex->lock();
117  }
118 
124  bool
125  trylock(Mutex* mutex)
126  {
127  unlock();
128  ASSERTD(mutex != nullptr);
129  if (mutex->trylock())
130  {
131  _mutex = mutex;
132  return true;
133  }
134  else
135  {
136  return false;
137  }
138  }
139 
141  void
143  {
144  if (_mutex != nullptr)
145  {
146  _mutex->unlock();
147  _mutex = nullptr;
148  }
149  }
150 
151 private:
152  Mutex* _mutex;
153 };
154 
156 
157 UTL_NS_END;
Named object mix-in.
Definition: NamedObjectMI.h:24
void unlock()
Unlock the Mutex.
Definition: Mutex.h:142
void deInit()
De-initialize UTL++.
void lock(Mutex *mutex)
Lock a Mutex.
Definition: Mutex.h:111
MutexGuard(Mutex *mutex)
Constructor.
Definition: Mutex.h:93
#define UTL_CLASS_DECL(DC, BC)
Declaration of standard UTL++ functionality for a non-template class.
Definition: macros.h:688
MutexGuard()
Default constructor.
Definition: Mutex.h:84
MUTual EXclusion device.
Definition: Mutex.h:27
bool trylock(Mutex *mutex)
Lock a new Mutex.
Definition: Mutex.h:125
Condition variable.
Definition: ConditionVar.h:30
~MutexGuard()
Destructor.
Definition: Mutex.h:101
#define UTL_CLASS_NO_COPY
Declare that a class cannot do copy().
Definition: macros.h:358
bool trylock()
Try to obtain the lock (without blocking).
void lock()
Obtain the lock (blocking if necessary).
Root of UTL++ class hierarchy.
Definition: Object.h:52
void init()
Initialize UTL++.
#define ASSERTD
Do an assertion in DEBUG mode only.
Acquire/release a Mutex RAII-style.
Definition: Mutex.h:80