Do thread die?
Steve Horsley
steve.horsley at gmail.com
Sat Sep 17 08:34:49 EDT 2005
Maurice LING wrote:
> Hi,
>
> I just have a simple question about threads. My classes inherits from
> threading.Thread class. I am calling threading.Thread.run() method to
> spawn a few threads to parallel some parts of my program. No thread
> re-use, pooling, joining ... just plainly spawn a thread, run a routine.
>
> So, at the end of run(), what happens to the thread? Just die?
As far as you are concerned, yes. They really just return to
wherever they came from. How they get created before they call
the run() method, and where they go after run() returns is down
to the implementation of the interpreter. Your code never sees
them before or after.
>
> While I am on it, can threading.Thread.run() accept any parameters?
>
No. But you can override it in a subclass.
> My current implementation may be ugly. I have a class
>
> class myThread(threading.Thread):
> def __init__(self, func):
> self.func = func
> threading.Thread.__init__(self)
> def run(self):
> print '%s function running' % self.func
> self.func()
>
> which is used in
>
> class myClass: #using myThread
> def __init__(self): pass
> def aFunc(self): pass
> def bFunc(self): pass
> def runAll(self):
> myThread(self.aFunc).start()
> myThread(self.bFunc).start()
There is a school of thought that says that a derived object
should never be altered such that it cannot be used as its parent
could. I happen to agree largely with this. Now, your MyThread
implementation is _reducing_ the functionality of its ancestor
Thread object such that you could not use a myThread in place of
a Thread. I believe that you should not be subclassing Thread to
do this. Your myClass doesn't need it anyway. Look at this
modified myClass:
class myClass2:
def aFunc(self): pass
def bFunc(self): pass
def runAll(self):
threading.Thread(target=self.aFunc).start()
threading.Thread(target=self.bFunc).start()
Steve
More information about the Python-list
mailing list