Do thread die?

Bryan Olson fakeaddress at nowhere.org
Sat Sep 17 12:24:04 CEST 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?

Just die, mostly. It may do a bit of clean-up, setting its
affairs in order, arraning for burial/cremation/organ-donation
and such, to avoid leaving any problem for posterity.


Incidentally, the "threading" module, with its "Thread" class,
has one major advantage over the "thread" module: the "setDaemon"
method of class Thread.


 > While I am on it, can threading.Thread.run() accept any parameters?

Not unless you override it; but you can pass parameters when
constructing the Thread, like this:

t = Thread(target=work_to_do, args=(67, 'Bill Johnston'), kwargs=some_dict)

t.start() will then execute the default Thread.run(), which
will execute work_to_do with two positional arguments -- 67 and
'Bill Johston' -- and whatever key-word arguments were in some_dict.

If you override 'Thread.run', you can define your override to take
whatever parameters you want.


 > 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()

[...]

 > Is this a good way?

I don't see anything wrong with it, though to me, it seems a
little heavy. To run your func, all you need to do is:

     Thread(target=func).start()

Though nine times out of ten, you'd want:

     t = Thread(target=func, args=(arg1, arg2, and_so_on))
     t.setDaemon(True)
     t.start()

If you really need that "print", you could build it into your
'target' function; or you could subclass Thread more generally,
so your subclass adds the print and behaves exactly the same
otherwise. I regard debugging as important, but I do not
believe that this  particular print warrants the general
inclusion implied.


Other Pythoners have disagree with me on various matters at
issue here. In particular, others have disagreed with my
advocacy of multiple lines of execution.


-- 
--Bryan



More information about the Python-list mailing list