Directly calling threaded class instance methods and attributes

Peter Otten __peter__ at
Thu Oct 28 13:18:07 CEST 2004

Matthew Bell wrote:

> import threading
> from time import sleep
> class SimpleThread(threading.Thread):
> def __init__(self):
> = 0
> threading.Thread.__init__(self)
> def add(self, number):
> += number
> def run(self):
> while(True):
> # In reality, there'd be much more here
> sleep(1)
> adder = SimpleThread()
> adder.start()
> for i in range(20):
> adder.add(1)
> print
> -------------------------------------------------------------------
> 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

I know _very_ little about threads, so forgive me if my conclusion that you
know even less is wrong. From what I see in your example you do not have
any data that is shared by multiple threads - total just happens to be
stored in a SimpleThread object but is never accessed by it.

I have tried to desimplify your code a bit

import time
from time import sleep
import threading

class SimpleThread(threading.Thread):
    def __init__(self): = 0
    def add(self, number):
        total =
        sleep(.3) = total + number
    def run(self):
        for i in range(10):

adder = SimpleThread()
for i in range(10):
print "total:",

and here's the output:

$ python
total: 12

I don't know whether += number

is atomic, but even if it were, I wouldn't rely on it. 
Conclusion: stick with queues, or wait for an expert's advice - or both :-)


More information about the Python-list mailing list