Remove lockFor... and expand ReadWriteLockable

This commit is contained in:
Atlante45 2015-11-10 18:19:12 -08:00
parent 3557eacbd0
commit 7cf2ad2215

View file

@ -9,54 +9,118 @@
#pragma once
#ifndef hifi_ReadWriteLockable_h
#define hifi_ReadWriteLockable_h
#include <utility>
#include <QtCore/QReadWriteLock>
#include "QTryReadLocker.h"
#include "QTryWriteLocker.h"
class ReadWriteLockable {
public:
// Write locks
template <typename F>
bool withWriteLock(F f, bool require = true) const {
if (!require) {
bool result = _lock.tryLockForWrite();
if (result) {
f();
_lock.unlock();
}
return result;
}
QWriteLocker locker(&_lock);
f();
return true;
}
bool withWriteLock(F f) const;
template <typename F>
bool withWriteLock(F&& f, bool require) const;
template <typename F>
bool withTryWriteLock(F f) const {
return withWriteLock(f, false);
}
bool withTryWriteLock(F f) const;
template <typename F>
bool withReadLock(F f, bool require = true) const {
if (!require) {
bool result = _lock.tryLockForRead();
if (result) {
f();
_lock.unlock();
}
return result;
}
QReadLocker locker(&_lock);
f();
return true;
}
bool withTryWriteLock(F f, int timeout) const;
// Read locks
template <typename F>
bool withTryReadLock(F f) const {
return withReadLock(f, false);
}
bool withReadLock(F f) const;
template <typename F>
bool withReadLock(F&& f, bool require) const;
template <typename F>
bool withTryReadLock(F f) const;
template <typename F>
bool withTryReadLock(F f, int timeout) const;
private:
mutable QReadWriteLock _lock{ QReadWriteLock::Recursive };
};
// ReadWriteLockable
template <typename F>
inline bool ReadWriteLockable::withWriteLock(F f) const {
QWriteLocker locker(&_lock);
f();
return true;
}
template <typename F>
inline bool ReadWriteLockable::withWriteLock(F&& f, bool require) const {
if (require) {
return withWriteLock(std::forward<F>(f));
} else {
return withTryReadLock(std::forward<F>(f));
}
}
template <typename F>
inline bool ReadWriteLockable::withTryWriteLock(F f) const {
QTryWriteLocker locker(&_lock);
if (locker.isLocked()) {
f();
return true;
}
return false;
}
template <typename F>
inline bool ReadWriteLockable::withTryWriteLock(F f, int timeout) const {
QTryWriteLocker locker(&_lock, timeout);
if (locker.isLocked()) {
f();
return true;
}
return false;
}
template <typename F>
inline bool ReadWriteLockable::withReadLock(F f) const {
QReadLocker locker(&_lock);
f();
return true;
}
template <typename F>
inline bool ReadWriteLockable::withReadLock(F&& f, bool require) const {
if (require) {
return withReadLock(std::forward<F>(f));
} else {
return withTryReadLock(std::forward<F>(f));
}
}
template <typename F>
inline bool ReadWriteLockable::withTryReadLock(F f) const {
QTryReadLocker locker(&_lock);
if (locker.isLocked()) {
f();
return true;
}
return false;
}
template <typename F>
inline bool ReadWriteLockable::withTryReadLock(F f, int timeout) const {
QTryReadLocker locker(&_lock, timeout);
if (locker.isLocked()) {
f();
return true;
}
return false;
}
#endif