PDA

View Full Version : Check if QReadWriteLock is locked



mentalmushroom
26th September 2016, 09:49
As the title suggests my question is how to check whether QReadWriteLock is locked (either for reading or writing). It seems there is no such method.

I am thinking of the options:

0x1) Use tryLockForWrite(0)
The drawback is that it would require calling unlock() and, probably, have negative impact on performance. Moreover, it doesn't work when QReadWriteLock is recursive.

0x2) Encapsulate the lock counter in the class along with QReadWriteLock. That should work in the recursive case, but it's more complex and requires additional care to protect the counter itself:


template <bool recursive>
class Lockable
{
public:
void lockForRead() const
{
this->lock.lockForRead();
this->locked.fetchAndAddRelease(1);
}

void lockForWrite()
{
this->lock.lockForWrite();
this->locked.fetchAndAddRelease(1);
}

void unlock() const
{
this->lock.unlock();
this->locked.fetchAndAddRelease(-1);
}

protected:
Lockable(): lock(recursive ? QReadWriteLock::Recursive : QReadWriteLock::NonRecursive) {}
Lockable(const Lockable &other) = delete;
Lockable(Lockable &&other) = default;
~Lockable() //= default;
{
// if the lock is still not released we have a critical error
//if (!lock.tryLockForWrite())
if (this->locked)
qFatal("Destroying lockable resource which is in use.");
}
private:
mutable QReadWriteLock lock;
mutable QAtomicInt locked = 0;
}; // Lockable




In the end it does make me wonder why Qt has no implementation of this method? Should I request this feature?

anda_skoa
26th September 2016, 10:40
Information like that is so transient that you can't really make any decision on it, i.e. the actual state could change the very moment after you have read it.

This unreliability is most likely why this is not part of the class itself, as it would incur overhead for basically no gain.

Cheers,
_