How to lock files (the easiest/best way)?

Donn Cave donn at u.washington.edu
Mon Jul 17 14:00:48 EDT 2006


In article <pan.2006.07.15.22.07.56.438428 at jippii.fi>,
 Elmo Mäntynen <elmo13 at jippii.fi> wrote:

> On Sat, 15 Jul 2006 23:52:10 +0200, Sybren Stuvel wrote:
> 
> > Elmo Mäntynen enlightened us with:
> >> Only locally. I want to be able to read/write to a single file from
> >> multiple possibly parallel processes. Would 'touch lock' (or
> >> something like that) work reliably (this just occured to me)?
> > 
> > I use a lock directory for that, os.mkdir('/var/lock/somedir').
> > If you use a file, you need two steps:
> >     1) Check whether the lock-file exists
> >     2) Create the lock-file
> > 
> > This is not atomic. With a directory, creating it will fail if it
> > already exists. This means you can atomically check for the lock, and
> > if it doesn't exist already, you've immediately created it too.
> > 
> > Sybren
> 
> Thanks. Is that what atomic basically means?

Yes, and also "race condition".  That's why Jim Segrave's
example code uses O_EXCL with open(2).

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list