libfilezilla
mutex.hpp
Go to the documentation of this file.
1 #ifndef LIBFILEZILLA_MUTEX_HEADER
2 #define LIBFILEZILLA_MUTEX_HEADER
3 
7 #include "libfilezilla.hpp"
8 #include "time.hpp"
9 
10 #ifdef FZ_WINDOWS
11 #include "private/windows.hpp"
12 #else
13 #include <pthread.h>
14 #endif
15 
16 namespace fz {
17 
27 class FZ_PUBLIC_SYMBOL mutex final
28 {
29 public:
30  explicit mutex(bool recursive = true);
31  ~mutex();
32 
33  mutex(mutex const&) = delete;
34  mutex& operator=(mutex const&) = delete;
35 
37  void lock();
38 
40  void unlock();
41 
42 private:
43  friend class condition;
44  friend class scoped_lock;
45 
46 #ifdef FZ_WINDOWS
47  CRITICAL_SECTION m_;
48 #else
49  pthread_mutex_t m_;
50 #endif
51 };
52 
61 class FZ_PUBLIC_SYMBOL scoped_lock final
62 {
63 public:
64  explicit scoped_lock(mutex& m)
65  : m_(&m.m_)
66  {
67 #ifdef FZ_WINDOWS
68  EnterCriticalSection(m_);
69 #else
70  pthread_mutex_lock(m_);
71 #endif
72  }
73 
74  ~scoped_lock()
75  {
76  if (locked_) {
77 #ifdef FZ_WINDOWS
78  LeaveCriticalSection(m_);
79 #else
80  pthread_mutex_unlock(m_);
81 #endif
82  }
83 
84  }
85 
86  scoped_lock(scoped_lock const&) = delete;
87  scoped_lock& operator=(scoped_lock const&) = delete;
88 
93  void lock()
94  {
95  locked_ = true;
96 #ifdef FZ_WINDOWS
97  EnterCriticalSection(m_);
98 #else
99  pthread_mutex_lock(m_);
100 #endif
101  }
102 
107  void unlock()
108  {
109  locked_ = false;
110 #ifdef FZ_WINDOWS
111  LeaveCriticalSection(m_);
112 #else
113  pthread_mutex_unlock(m_);
114 #endif
115  }
116 
117 private:
118  friend class condition;
119 
120 #ifdef FZ_WINDOWS
121  CRITICAL_SECTION * const m_;
122 #else
123  pthread_mutex_t * const m_;
124 #endif
125  bool locked_{true};
126 };
127 
132 class FZ_PUBLIC_SYMBOL condition final
133 {
134 public:
135  condition();
136  ~condition();
137 
138  condition(condition const&) = delete;
139  condition& operator=(condition const&) = delete;
140 
147  void wait(scoped_lock& l);
148 
160  bool wait(scoped_lock& l, duration const& timeout);
161 
171  void signal(scoped_lock& l);
172 
180  bool signalled(scoped_lock const&) const { return signalled_; }
181 private:
182 #ifdef FZ_WINDOWS
183  CONDITION_VARIABLE cond_;
184 #else
185  pthread_cond_t cond_;
186 #endif
187  bool signalled_{};
188 };
189 
190 }
191 #endif
bool signalled(scoped_lock const &) const
Check if condition is already signalled.
Definition: mutex.hpp:180
A simple scoped lock.
Definition: mutex.hpp:61
Waitable condition variable.
Definition: mutex.hpp:132
void lock()
Obtains the mutex.
Definition: mutex.hpp:93
Assorted classes dealing with time.
void unlock()
Releases the mutex.
Definition: mutex.hpp:107
The namespace used by libfilezilla.
Definition: apply.hpp:16
The duration class represents a time interval in milliseconds.
Definition: time.hpp:271
Sets some global macros and further includes string.hpp.
Lean replacement for std::(recursive_)mutex.
Definition: mutex.hpp:27