[mod_python] Re: Creating a thread-safe handler

Stian Søiland stian at soiland.no
Sat May 15 15:29:24 EDT 2004


On 2004-05-15 12:16:46, Geert Jansen wrote:

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

A module import is threadsafe[1], so the simple thing to do is:

lock = Lock()
def my_handler(req):
    lock.acquire()
    ...
    lock.unlock()
     

     
.. [1] http://www.python.org/doc/current/lib/module-imp.html

    lock_held(  )   
    
    Return True if the import lock is currently held, else False. On platforms
    without threads, always return False. 

    On platforms with threads, a thread executing an import holds an internal
    lock until the import is complete. This lock blocks other threads
    from doing an import until the original import completes, which in
    turn prevents other threads from seeing incomplete module objects
    constructed by the original thread while in the process of
    completing its import (and the imports, if any, triggered by that).     

-- 
Stian Søiland               Work toward win-win situation. Win-lose
Trondheim, Norway           is where you win and the other lose.
http://www.soiland.no/      Lose-lose and lose-win are left as an
                            exercise to the reader.  [Limoncelli/Hogan]
                            Og dette er en ekstra linje 



More information about the Mod_python mailing list