added locker classes intended to be used with QMutex

This commit is contained in:
Martchus 2016-03-10 22:15:16 +01:00
parent ed9fbc44cd
commit 98897b26f8
4 changed files with 100 additions and 1 deletions

View File

@ -8,6 +8,8 @@ set(HEADER_FILES
misc/desktoputils.h
misc/xmlparsermacros.h
misc/undefxmlparsermacros.h
misc/trylocker.h
misc/adoptlocker.h
models/checklistmodel.h
resources/qtconfigarguments.h
resources/resources.h

38
misc/adoptlocker.h Normal file
View File

@ -0,0 +1,38 @@
#ifndef ADOPTLOCKER_H
#define ADOPTLOCKER_H
#include <QtGlobal>
QT_FORWARD_DECLARE_CLASS(QMutex)
namespace ThreadingUtils {
/*!
* \brief Like QMutexLocker, but assumes that the mutex has already been locked.
*/
template<typename Mutex = QMutex>
class AdoptLocker
{
public:
/*!
* \brief Constructs the locker for the specified \a mutex.
*/
AdoptLocker(Mutex &mutex) :
m_mutex(mutex)
{}
/*!
* \brief Unlocks the mutex specified when constructing the instance.
*/
~AdoptLocker()
{
m_mutex.unlock();
}
private:
Mutex &m_mutex;
};
}
#endif // ADOPTLOCKER_H

57
misc/trylocker.h Normal file
View File

@ -0,0 +1,57 @@
#ifndef TRYLOCKER_H
#define TRYLOCKER_H
#include <QtGlobal>
QT_FORWARD_DECLARE_CLASS(QMutex)
namespace ThreadingUtils {
/*!
* \brief Like QMutexLocker, but it just tries to lock the mutex.
*/
template<typename Mutex = QMutex>
class TryLocker
{
public:
/*!
* \brief Tries to lock the specified mutex.
*/
TryLocker(Mutex &mutex) :
m_mutex(mutex.tryLock() ? &mutex : nullptr)
{}
/*!
* \brief Unlocks the mutex specified when constructing.
* \remarks Does nothing if the mutex couldn't be locked in the first place.
*/
~TryLocker()
{
if(m_mutex) {
m_mutex->unlock();
}
}
/*!
* \brief Returns whether the mutex could be locked.
*/
bool isLocked() const
{
return m_mutex != nullptr;
}
/*!
* \brief Returns whether the mutex could be locked.
*/
operator bool() const
{
return m_mutex != nullptr;
}
private:
Mutex *m_mutex;
};
}
#endif // TRYLOCKER_H

View File

@ -32,7 +32,9 @@ HEADERS += \
misc/dialogutils.h \
misc/desktoputils.h \
misc/xmlparsermacros.h \
misc/undefxmlparsermacros.h
misc/undefxmlparsermacros.h \
misc/trylocker.h \
misc/adoptlocker.h
SOURCES += resources/resources.cpp \
models/checklistmodel.cpp \