Directly calling threaded class instance methods and attributes

Josiah Carlson jcarlson at uci.edu
Thu Oct 28 19:58:13 CEST 2004


lights at cix.co.uk (Matthew Bell) wrote:
> 
> Hi,
> 
> I've got a question about whether there are any issues with directly 
> calling attributes and/or methods of a threaded class instance.  I
> wonder if someone could give me some advice on this.

No problem.

[Snip code and text]

> If anyone could let me know either "Yeah, that's fine" or "NO!!! That
> can break <foo> / cause a deadlock in <bar> / etc!!!" I'd be much 
> obliged.

With what you offered, it would not cause a deadlock, though it would
cause what is known as a race condition, where two threads are trying to
modify the same variable at the same time.  Note that attributes of a
thread object are merely attributes of an arbitrary Python object, so
nothing special happens with them.


Here is a far more telling example...
>>> import threading
>>> val = 0
>>> def foo(n):
...     global val
...     for i in xrange(n):
...         val += 1
...
>>> for i in xrange(10):
...     threading.Thread(target=foo, args=(100000,)).start()
...
>>> #wait a few seconds...
... 
>>> val
202229
>>>

If there were no race condition, that value should be 1000000.  Let us
use locks to fix it.

>>> val2 = 0
>>> lock = threading.Lock()
>>> def goo(n):
...     global val2, lock
...     for i in xrange(n):
...         lock.acquire()
...         val2 += 1
...         lock.release()
...
>>> for i in xrange(10):
...     threading.Thread(target=goo, args=(100000,)).start()
...
>>> #wait...
...
>>> val2
1000000


 - Josiah




More information about the Python-list mailing list