When is a thread garbage collected?
"Martin v. Löwis"
martin at v.loewis.de
Wed Mar 16 23:28:20 CET 2005
Kent Johnson wrote:
> If I create and start a thread without keeping a reference to the
> thread, when is the thread garbage collected?
When the last reference to the Thread disappears, which is definitely
after the thread terminates.
(Notice that this sentence uses the word thread twice: once to denote
the operating system schedulable unit, and once to denote the Python
object. Only the Python object is subject to garbage collection; the
operating system schedulable unit is not)
> For example with this code:
> def genpassenger(num):
> for i in range(num):
> class passenger(threading.Thread):
> def run:
> #do something
> will all the passenger threads run to completion, then be GCed?
In this example, you'll get a syntax error, because the syntax
for the run method is wrong. If you correct the example, the
answer to the question you asked literally is "yes", but this
is likely not the question you meant to ask. Instead, it might
be that you meant to ask "... then immediately be GCed?" to
which the answer is "it depends on the body of #do something".
IOW, the Thread object may live much longer than the end of the
More information about the Python-list