in reply to Ways to sequence calls from multiple processes
- Process A opens lock.txt
- Process B opens lock.txt
- Process A flocks()
- Process B tries to flock().... and fails
If you want to be more safe, you should ask yourself: what happens if now_access_the_common_resource() crashes or loops? will the file stay locked forever? how do you detect that the other processes are starving?
My suggestion is: if your program already uses a RDBMS, why not using its own locking features? each and every decent RDBMS already has consistent locking features implemented to make its own basic work.
You could - for example - have a one-row table with a status field that each process tries to update like UPDATE mytable SET status=1 WHERE status=0 LIMIT 1. After each update you check the number of affected rows; it it's 1 you got access to the resource (and atomically locked it), if no row was affected you could not obtain the access, so you sleep() random seconds and try again. To release the resource you simply UPDATE mytable SET status = 0 WHERE table_id = 123.
The nice part of this approach is that it works not only for one resource but for limited sets like resource pools too: just add ten lines to the table, and the first ten processes will be allowed to pass, the eleventh will have to wait and so on.