I am using flock(2) in linux to control access to resources in a homespun database, using both shared and exclusive locking modes. I find that if a shared lock is granted, then another process can also get a shared lock, regardless of whether there are blocked processes waiting for exclusive locks. This means that for a popular resource with many overlapping readers, an exclusive lock request can starve for a long time, perhaps forever.
This behavior does not contradict the flock(2) man page, but it surprises me because this code has been working for years in FreeBSD and OS-X without a problem. My guess is that BSD systems must implement some kind of queue to prevent exclusive locks from starving forever.
My primary question is, is there any simple trick or programming pattern to keep my exclusive locks from starving?
A secondary question, to satisfy my curiousity, does anyone know if this really is different on BSD systems like I suspect?
I had exactly same problem on FreeBSD 7.2 and found no way to prevent writer starvation on flock(). You have to choose other locking method, like SysV IPC or simple stop-flag file.