Directly calling threaded class instance methods and attributes

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


Matthew Bell wrote:

> import threading
> from time import sleep
> 
> class SimpleThread(threading.Thread):
> def __init__(self):
> self.total = 0
> threading.Thread.__init__(self)
> 
> def add(self, number):
> self.total += 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 adder.total
> -------------------------------------------------------------------
> 
> 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):
        self.total = 0
        threading.Thread.__init__(self)
    
    def add(self, number):
        total = self.total
        sleep(.3)
        self.total = total + number
    
    def run(self):
        for i in range(10):
            sleep(.1)
            self.add(1)

adder = SimpleThread()
adder.start()
for i in range(10):
    adder.add(1)
adder.join()
print "total:", adder.total

and here's the output:

$ python testthread.py
total: 12
$

I don't know whether 

self.total += 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 :-)

Peter




More information about the Python-list mailing list