[mod_python] Creating a thread-safe handler

Geert Jansen geert at boskant.nl
Sat May 15 13:16:46 EDT 2004


I am trying to make my mod_python application thread safe so it can be
run on Windows. Not everything is completely clear to me yet, so
hopefully someone can help me out.

Python threads run in the same sub-interpreter, so you need some kind of
synchronization when handling global objects. A threading.Lock can help
here. However, how can such a lock be safely created? The lock itself
must be a global object as well.

For example:

def my_handler(req):
    global lock
    except NameError:
        lock = Lock()   # XXX: not thread safe!
        lock.acquire()  # Lock could be created by another thread
   # do thread-unsafe stuff here

A solution seems to be to use PythonImport to pre-import the handler
module. Because that's run when a child is started, I assume no threads
have been created yet and a global Lock can be safely set up. But this
seems a hack. Any ideas?

Geert Jansen

More information about the Mod_python mailing list