I had been looking for a way to synchronize my python cgi scripts (several, or several instances of one) so that only one of them could access a particular table in a database at one time.  I looked around on the internet but didn’t find a concrete class that could do this.  I was writing my scripts for a linux based apache server, so portability didn’t matter. So here it is.

#!/usr/bin/python
#
import os
import fcntl

class lock:
        def __init__(self):
                self.lockf = 0
                self.file = 0

        def lock(self):
                self.lockf = open ('/tmp/mytmpfilename.1001', 'a')
                fcntl.flock (self.lockf, fcntl.LOCK_EX)
                self.file = open ('/tmp/mytmpfilename.1001','w')

        def unlock(self):
                self.file.close ()
                self.lockf.close ()

###

If you know of a better way of synchronizing processes, please let me know.

Edit.10/21/2008:

Here is more specifically what my scripts do. Perhaps, this post makes more sense in the correct context. The description below was taken from one of my comments.

All instances of my cgi script perform a read operation followed by a delete operation. Essentially, my script reads the top row from the database. Right after the information is retrieved that particular row is deleted. In other words, I am using my database as a FIFO buffer. Now if several instances of my scripts are running, more than one of them could access the first row (read it), thereby letting two different processes fetch the same element from a FIFO. One but all of them then fails with the deletion operation. The whole idea behind this locking mechanism was to avoid this. All instances of my script should always fetch a different item.

/