Threading Oddity?

Kevin other at cazabon.com
Sat Aug 23 01:22:04 EDT 2003


use this instead and you're fine:

import threading
data_mutex = threading.Lock()

using the thread module directly is depreciated, and the threading.Lock()
object works as you expect without having to check if it's locked before
acquiring it.

Kevin




"Kris Caselden" <google at hanger.snowbird.net> wrote in message
news:abc3fdd3.0308222033.78c460ab at posting.google.com...
> 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