When is a thread garbage collected?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Kent Johnson

    When is a thread garbage collected?

    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(nu m):
    for i in range(num):
    passenger().sta rt()

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

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

    Thanks,
    Kent
  • Martin v. Löwis

    #2
    Re: When is a thread garbage collected?

    Kent Johnson wrote:[color=blue]
    > If I create and start a thread without keeping a reference to the
    > thread, when is the thread garbage collected?[/color]

    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)
    [color=blue]
    > For example with this code:
    >
    > def genpassenger(nu m):
    > for i in range(num):
    > passenger().sta rt()
    >
    > class passenger(threa ding.Thread):
    > def run:
    > #do something
    >
    > will all the passenger threads run to completion, then be GCed?[/color]

    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

    Comment

    Working...