Reputation: 5475
I was going through the completely fair solution to the Readers/Writers problem, and the order of releasing locks seems confusing to me. I'd like to know if we could swap the order of releasing the serviceQueue
lock and the readCountAccess
lock in the reader()
function. It seems counter-intuitive to release the locks in this manner if the order doesn't matter. But I don't see what's wrong in releasing the locks in the opposite order (first readCountAccess
and then then serviceQueue
lock).
Upvotes: 1
Views: 54
Reputation: 16357
This is probably a remnant from the days where you could justify first releasing the broader lock (in this case serviceQueue
) if that doesn't affect correctness, because another thread can immediately proceed with acquiring it while you are releasing the more narrow lock.
Imagine that each acquire or release takes 1 time unit, each other operation takes 0 time units, a reader just incremented the reader counter at time 0, and there's another reader next in line in the service wait queue.
If readCountAccess
is released first and serviceQueue
second, the next reader could acquire the serviceQueue
mutex no earlier than at time 3. Therefore the earliest it can be done with the read lock registration ceremony is at time 6. The benefiting party here will be other readers waiting to exit, and they are less important, because they shouldn't be able to also release resourceAccess
(because our original reader has just registered as such).
If on the other hand serviceQueue
is released first and readCountAccess
second, the next reader could acquire the serviceQueue
mutex as early as at time 2. This means that it can be done with the read lock registration ceremony as early as at time 5.
I'd still prefer to unlock using a symmetric scheme though - it is less error-prone, it has broader recognition, and the burden of proof that currently it's worse in any way than the version above will lie on the shoulders of the doubters.
Upvotes: 1