When is a thread garbage collected?

K

Kent Johnson

If I create and start a thread without keeping a reference to the thread, when is the thread garbage
collected?

What I would like is for the thread to run to completion, then be GCed. I can't find anything in the
docs that specifies this behavior; nor can I think of any other behaviour that seems reasonable :)

For example with this code:

def genpassenger(num):
for i in range(num):
passenger().start()

class passenger(threading.Thread):
def run:
#do something

will all the passenger threads run to completion, then be GCed?

Thanks,
Kent
 
?

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

Kent said:
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):
passenger().start()

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
thread.

Regards,
Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top