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:
Qt Code:
  1. template <bool recursive>
  2. class Lockable
  3. {
  4. public:
  5. void lockForRead() const
  6. {
  7. this->lock.lockForRead();
  8. this->locked.fetchAndAddRelease(1);
  9. }
  10.  
  11. void lockForWrite()
  12. {
  13. this->lock.lockForWrite();
  14. this->locked.fetchAndAddRelease(1);
  15. }
  16.  
  17. void unlock() const
  18. {
  19. this->lock.unlock();
  20. this->locked.fetchAndAddRelease(-1);
  21. }
  22.  
  23. protected:
  24. Lockable(): lock(recursive ? QReadWriteLock::Recursive : QReadWriteLock::NonRecursive) {}
  25. Lockable(const Lockable &other) = delete;
  26. Lockable(Lockable &&other) = default;
  27. ~Lockable() //= default;
  28. {
  29. // if the lock is still not released we have a critical error
  30. //if (!lock.tryLockForWrite())
  31. if (this->locked)
  32. qFatal("Destroying lockable resource which is in use.");
  33. }
  34. private:
  35. mutable QReadWriteLock lock;
  36. mutable QAtomicInt locked = 0;
  37. }; // Lockable
To copy to clipboard, switch view to plain text mode 


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