2016-07-04 23:26:48 +02:00
|
|
|
#ifndef THREADING_UTILS_TRYLOCKER_H
|
|
|
|
#define THREADING_UTILS_TRYLOCKER_H
|
2016-03-10 22:15:16 +01:00
|
|
|
|
|
|
|
#include <QtGlobal>
|
|
|
|
|
|
|
|
QT_FORWARD_DECLARE_CLASS(QMutex)
|
|
|
|
|
|
|
|
namespace ThreadingUtils {
|
|
|
|
|
|
|
|
/*!
|
|
|
|
* \brief Like QMutexLocker, but it just tries to lock the mutex.
|
|
|
|
*/
|
2017-05-01 03:16:25 +02:00
|
|
|
template <typename Mutex = QMutex> class TryLocker {
|
2016-03-10 22:15:16 +01:00
|
|
|
public:
|
|
|
|
/*!
|
2017-05-04 22:46:37 +02:00
|
|
|
* \brief Tries to lock the specified mutex.
|
|
|
|
*/
|
2017-05-01 03:16:25 +02:00
|
|
|
TryLocker(Mutex &mutex)
|
|
|
|
: m_mutex(mutex.tryLock() ? &mutex : nullptr)
|
|
|
|
{
|
|
|
|
}
|
2016-03-10 22:15:16 +01:00
|
|
|
|
|
|
|
/*!
|
2017-05-04 22:46:37 +02:00
|
|
|
* \brief Unlocks the mutex specified when constructing.
|
|
|
|
* \remarks Does nothing if the mutex couldn't be locked in the first place.
|
|
|
|
*/
|
2016-03-10 22:15:16 +01:00
|
|
|
~TryLocker()
|
|
|
|
{
|
2017-05-01 03:16:25 +02:00
|
|
|
if (m_mutex) {
|
2016-03-10 22:15:16 +01:00
|
|
|
m_mutex->unlock();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
2017-05-04 22:46:37 +02:00
|
|
|
* \brief Returns whether the mutex could be locked.
|
|
|
|
*/
|
2016-03-10 22:15:16 +01:00
|
|
|
bool isLocked() const
|
|
|
|
{
|
|
|
|
return m_mutex != nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
/*!
|
2017-05-04 22:46:37 +02:00
|
|
|
* \brief Returns whether the mutex could be locked.
|
|
|
|
*/
|
2016-03-10 22:15:16 +01:00
|
|
|
operator bool() const
|
|
|
|
{
|
|
|
|
return m_mutex != nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
Mutex *m_mutex;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2016-07-04 23:26:48 +02:00
|
|
|
#endif // THREADING_UTILS_TRYLOCKER_H
|