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

Paul Rubin http
Sat Jul 15 20:04:41 EDT 2006


Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> writes:
> 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.

The classic way in Unix was to make a link:

   1) link('some_other_file', 'lockfile')

This was atomic and would fail if lockfile already existed.

I'm not sure whether it can still be reliable, in current environments
that can involve remote file systems etc.  But I'm not sure if the
mkdir approach works either.

Maybe you want to use something like shm or posh?



More information about the Python-list mailing list