Qt Utilities  5.6.0
Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models
trylocker.h
Go to the documentation of this file.
1 #ifndef THREADING_UTILS_TRYLOCKER_H
2 #define THREADING_UTILS_TRYLOCKER_H
3 
4 #include <QtGlobal>
5 
6 QT_FORWARD_DECLARE_CLASS(QMutex)
7 
8 namespace ThreadingUtils {
9 
13 template<typename Mutex = QMutex>
14 class TryLocker
15 {
16 public:
20  TryLocker(Mutex &mutex) :
21  m_mutex(mutex.tryLock() ? &mutex : nullptr)
22  {}
23 
29  {
30  if(m_mutex) {
31  m_mutex->unlock();
32  }
33  }
34 
38  bool isLocked() const
39  {
40  return m_mutex != nullptr;
41  }
42 
46  operator bool() const
47  {
48  return m_mutex != nullptr;
49  }
50 
51 private:
52  Mutex *m_mutex;
53 };
54 
55 }
56 
57 #endif // THREADING_UTILS_TRYLOCKER_H
bool isLocked() const
Returns whether the mutex could be locked.
Definition: trylocker.h:38
Like QMutexLocker, but it just tries to lock the mutex.
Definition: trylocker.h:14
TryLocker(Mutex &mutex)
Tries to lock the specified mutex.
Definition: trylocker.h:20
~TryLocker()
Unlocks the mutex specified when constructing.
Definition: trylocker.h:28