ReadWriteLock asserts

Is there some way of checking whether a ReadWriteLock is currently locked? I’ve got a couple of cases where it’d be useful to write some asserts for lower level code that checks that the higher level lock is in the expected locked state…

Can you achieve this with the tryEnterRead() and tryEnterWrite() methods? They will immediately return false if the ReadWriteLock is currently locked or true if the lock was successfully gained.


I expect that they may return true if I’m on the same thread that’s already holding the lock though…

You should only be using tryLock methods to check whether your object is locked, anything else if vulnerable to race conditions. One way around this is to use your own signalling mechanism which could be as simple as setting and unsetting a boolean flag when you enter and exit the lock.


That wasn’t my understanding from the manual. Maybe I’m reading it wrong?

Tries to lock this object for writing.
This is like enterWrite(), but doesn’t block - it returns true if it manages to obtain the lock.

From what you have written it looks like you should set a flag to indicate if a thread has the lock, then remove this flag just before you exit the lock. You can then check this flag to see the status. There really is no foolproof way to test whether a lock is active or not other than attempting to acquire it.

Yeah, I wasn’t really after foolproof, enough to just flag a warning if some code turn out to be executed from time to time without the lock held. I’ll put a wrapper around the lock maybe to add the flag…

Normally I’d try and keep all this shit in a nice easy-to-review class. But I’ve got a ton of sqlite stuff which is difficult to keep in one place in this project