Threading Oddity?

Jeff Epler jepler at unpythonic.net
Sun Aug 24 09:49:36 EDT 2003


On Fri, Aug 22, 2003 at 09:33:18PM -0700, Kris Caselden wrote:
> 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 didn't run for me (no lines were printed) because the program
exits when the main thread is done.  I added
	import time
	time.sleep(1)
after the start_new_thread calls as a remedy.  Then, it printed two
lines and waited about a second before I got the prompt back.

I tried removing the 'while's and dedenting the lines
"data_mutex.aquire".  Then I got an attribute error!

But with the "while", there's no error.  Why not?  Because the mutex was
never locked!  If the mutex is not locked, the body of the while statement
is not executed.  On the other hand, if the statement inside the loop
was executed and did successfully claim the mutex, the 'while' condition
would evaluate to 'true' the next time through, the statement to claim
the lock would execute again, and block forever.  (but this isn't likely
to happen on any particular run, because it would require that the mutex
be released at just the right moment.. properly testing threaded code is
hard)

I think this comes down to being a typo (as pointed out by another
poster, acquire vs aquire) and the addition of the 'while' loop just
adds confusion and is a completely wrong thing to do.

Jeff





More information about the Python-list mailing list