Directly calling threaded class instance methods and attributes

Matthew Bell lights at
Thu Oct 28 12:28:13 CEST 2004


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.

Generally, the documentation suggests that queues or similar constructs 
should be used for thread inter-process comms.  I've had a lot of 
success in doing that (generally by passing in the queue during the 
__init__ of the thread) and I can see situations where it's pretty much 
the only way of doing it.  But, there are other situations - 
particularly where you've got a "main" thread that creates, and is the
sole communicator with, one or more "worker" threads - where keeping 
track of the different queues can get a bit unwieldy.  

So I thought about it some more, and came to the conclusion that - 
again, in some situations - it could be a lot cleaner if you could call 
methods and/or access attributes of a threaded class instance directly.  
Here's some example code to show what I'm talking about:

import threading
from time import sleep

class SimpleThread(threading.Thread):
    def __init__(self): = 0

    def add(self, number): += number

    def run(self):
            # In reality, there'd be much more here

adder = SimpleThread()
for i in range(20):

This example code works.  Well, it does for me, anyway :-)  

My question is simply, can anyone see any issues with calling methods
and/or attributes of a threaded class instance like this?  It looks ok
to me but, as the docs never seem to mention using threads like this,
I'm wondering if I've missed something important.  If it helps, I 
know the basic considerations of threading, such as locking, exception
handling and so on; I only really need advice on whether there could
be issues with directly calling class instance attributes of a 
running thread.

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 


More information about the Python-list mailing list