cgi concurrency approaches?

Paul Rubin http
Fri Jan 23 00:06:32 EST 2004


I'm wondering if folks here have favorite lightweight ways of dealing
with concurrency in cgi's.  Take a simple case:

You want to write a cgi that implements a simple counter.  The first
time it's called, it prints "1".  The next time, "2", etc.  The naive
implementation looks something like:

   fd = open("counter.num", "rw")
   n = int(fd.read())
   fd.seek(0, 0)
   fd.write("%d"% n+1)
   print "Content-type: text/html\n\n"
   print n

but of course there's the obvious race condition if two people hit the
cgi at the same time.

Fancier solutions include running an transactional database in another
process and connecting to it, setting up a daemon that remembers the
counter value in memory and serializes access through a socket that
the cgi opens, using a file-system specific hack like linking to
counter file to lock it, having a timeout/retry if the counter is
locked, with a possible hangup if a lock file gets left around by
accident, etc.  Each is a big pain in the neck.

Anyone have some simpler approaches?



More information about the Python-list mailing list