Garbage collector and threads

Aahz aahz at pythoncraft.com
Mon Mar 1 17:26:57 CET 2004


In article <hgJ0c.4318$mx4.105259 at nnrp1.uunet.ca>,
Nicolas Fleury  <nid_oizo at yahoo.com_remove_the_> wrote:
>
>	I just discovered, correct me if I'm wrong, that as long as a 
>threading.Thread is running, its destructor will not be called, because 
>it is referring to himself.  So if I have something like:
>
>class MyThread(threading.Thread):
>     def __init__(self):
>         self.cancelEvent = threading.Event()
>         threading.Thread.__init__(self)
>     def __del__(self):
>         self.cancel()
>     def run(self):
>         self.cancelEvent.wait()
>     def cancel(self):
>         self.cancelEvent.set()
>
>I must call cancel from the outside if I want the destructor to be 
>called (note that I don't want deamon threads).  I can make a wrapper 
>over threading.Thread to have the behaviour I want: have a thread with 
>__del__ called when it is not referred by another thread.  But my 
>question is, and I don't have an overall vision of the issue at all, 
>should that be the default behaviour anyway?

Yes, Don't Do That.  Do not rely on finalizers for external resources
(such as threads).

Note that your understanding of Python's memory management could use some
improvement: GC *never* runs on objects containing __del__
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"Do not taunt happy fun for loops. Do not change lists you are looping over."
--Remco Gerlich, comp.lang.python



More information about the Python-list mailing list