Making sure script only runs once instance at a time.

Eric S. Johansson esj at harvee.org
Tue Oct 3 06:28:35 CEST 2006


MonkeeSage wrote:
> Here's a class using Fredrik's suggestions to provide generic,
> cross-platform file locking (only tested on *nix however, with the two
> test files listed [i.e., run test1.py in one terminal then test2.py in
> another]):
> 
> http://pastie.caboo.se/15851
> 
> Ps. The lockfile should also always be cleaned up (even when your
> program excepts) because of the magic __del__ method, but I don't
> guarentee it will be (nor depend on it: I used the pid + hostname in
> the lockfile approach).

the problem with this solution is that it does not handle the read 
nonexclusive/write exclusive locking model.  In this model, reads don't 
block, they only register that the request is in process.  writes lock 
request block until all outstanding reads have completed.  When there is 
a write lock waiting, all subsequent reads lock requests block until the 
write has completed.

Things get more complicated when you add exclusive read capability to 
the system.  But fortunately, that capability isn't needed very often 
and sometimes reduces to a write exclusive lock.

The next level up in terms of locking system requirements is some form 
of scoreboard mechanism where you can lock individual records in a file 
(i.e. dbm).  I do something like this in a demon which  owns the dbm, 
mediates database access, and record locking so that I can have multiple 
readers and writers at the same time using gdbm.  But you can also use 
the same technique for metakit.


---eric





More information about the Python-list mailing list