I need a "lock" that can be either shared or held exclusively, that will provide the following behavior for the following sequence of events:
- Process A: Requests and is granted a shared lock
- Process B: Requests an exclusive lock, and is blocked by A's ownership of the lock
- Process C: Requests a shared lock, and is blocked because B is in line for an exclusive lock
I had thought that the Unix flock
would provide these semantics, but then discovered that in step 3, Process C's request for a shared lock would succeed, and Process B's request for an exclusive lock would only be granted when there were no shared locks being held. This has the unfortunate (for me) effect that, the more concurrent processes there are requesting shared locks, the longer a process requesting an exclusive lock will have to wait for a window in which there are no outstanding shared locks being held.
The behavior I seek, in other words, is that, from the time that a process requests an exclusive lock, through the time that it is granted the lock and until the time that it releases the lock, all subsequent shared lock requests will be queued and blocked.
What type of lock has the properties that I need?