How do you lock your web app data?

Remco Gerlich scarblac at pino.selwerd.nl
Wed Jan 31 09:06:41 EST 2001


Gilles Lenfant <glenfant at equod.com.nospam> wrote in comp.lang.python:
> If you play with lot of small files and few users you can use "lock files"
> with the same name as the file the user is supposed to modify.
> This is not "pythonic" but a general algorythm that can be done in python or
> whatever:
> 
> start cgi
> if not exists "myfile.lock"
>   touch "myfile.lock"
>   # play with "myfile.txt"
>   ...
>   # end play with "myfile.txt"
>   rm "myfile.lock"
> else
>   reply "resource in use, come back later" to the user (or anything else
> relevant)
> endif
> end cgi

This doesn't work. First both threads check if the file doesn't exist, then
they both assume they're clear, make the file, and start corrupting each
other.

Something nearly like this does work, on Unix and Windows, as far as I know:
make a directory. This is guaranteed atomic (so they can't do it both at the
same time) and will give an exception when the directory already exists.

import os

def acquire_lock(filename):
   while 1:
      try:
         os.mkdir(filename+".lock")
         return
      except OSError:
         pass

def release_lock(filename):
   os.rmdir(filename+".lock")
   
acquire_lock("whee")
f = open("whee","a")
print >> f, "Whee!"
f.close()
release_lock("whee")

This is a very simplistic form of spinlock and you run into deadlock when
one of the processes bugs and doesn't release the lock, but simplicity is
good.

-- 
Remco Gerlich



More information about the Python-list mailing list