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
bart's criticisms of this approach are well taken, however, there are ways to take advantage of database locking to solve your problem. In Oracle, for example, you could have the same table described, but do a
SELECT FOR UPDATE mytable or even just
LOCK mytable. Then you would do your work on your resource. When you are finished, do a
ROLLBACK or
an
UNLOCK mytable. Most other RDBMS's will have similar, but not necessarily identical language to effect the same behavior. This has the advantage that if your code fails unexpectedly, the database will remove the lock for you. You have to be careful if the resource (or one of the resources) you access is the database itself; in that case doing the rollback will not have the results you want ;)
All that said, the file locking is still the simpler and more straightforward solution in most (99.9999%) cases.
--DrWhy
"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."