Threading Oddity?

Kris Caselden google at hanger.snowbird.net
Sat Aug 23 06:33:18 CEST 2003


I noticed a strange yet easily fixed problem in Python's thread
module.

Consider the following code:

#-------------------------------

import thread

data='this is data'
data_mutex = thread.allocate_lock()

def thread1():
    while data_mutex.locked():
        data_mutex.aquire()
    print 'thread1:',data
    if data_mutex.locked():
        data_mutex.release()

def thread2():
    while data_mutex.locked():
        data_mutex.aquire()
    print 'thread2:',data
    if data_mutex.locked():
        data_mutex.release()

thread.start_new_thread(thread1,())
thread.start_new_thread(thread2,())

#-------------------------------

This code runs as expected. However, take away the while loop checks
for mutex lock and Python is unable to properly acquire the lock,
complaining of an unhandled exception. The Python Library Reference
mentions that "this method acquires the lock unconditionally, if
necessary waiting until it is released by another thread (only one
thread at a time can acquire a lock -- that's their reason for
existence), and returns None." You'd think one wouldn't have to check
if the lock is locked, especially when acquire is supposed to wait for
the lock to be freed. At first, I thought this problem had to do with
aquire()'s waitflag, but the problem exists regardless of waitflag's
value.

Does anyone know why this problem exists, and if my code works around
it? It would seem that locked() and acquire() would not necessarily be
run uninterrupted, and so mutual exclusion could not be guaranteed.




More information about the Python-list mailing list