| 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 QtUtilities { |
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
template <typename Mutex = QMutex> class TryLocker { |
| 14 |
public: |
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
TryLocker(Mutex &mutex) |
| 19 |
: m_mutex(mutex.tryLock() ? &mutex : nullptr) |
| 20 |
{ |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
~TryLocker() |
| 28 |
{ |
| 29 |
if (m_mutex) { |
| 30 |
m_mutex->unlock(); |
| 31 |
} |
| 32 |
} |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
bool isLocked() const |
| 38 |
{ |
| 39 |
return m_mutex != nullptr; |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
operator bool() const |
| 46 |
{ |
| 47 |
return m_mutex != nullptr; |
| 48 |
} |
| 49 |
|
| 50 |
private: |
| 51 |
Mutex *m_mutex; |
| 52 |
}; |
| 53 |
} |
| 54 |
|
| 55 |
#endif |