WhiskeyAndRye WhiskeyAndRye - 1 year ago 53
Python Question

Python - is `threading.Event` "set" during garbage collection?

The title of this post pretty much sums up my question - will threads waiting on an

be notified if that event has been garbage collected? In my particular case I have a class whose instances have an
as an attribute, and I'm wondering whether I should implement a
method on this class that calls
before it's garbage collected.

I'm new to asynchronicity, so if event's don't
when they're garbage collected, perhaps it's bad practice to do so, and better to let threads hang? Thanks in advance for any responses.

Answer Source

Note that it's not necessarily the case that waiting for an Event implies the Event isn't in trash. Cyclic trash is one possibility, and here's another:

import threading

class C(object):
    def __init__(self):
        self.e = threading.Event()

    def __del__(self):
        print("going away")

def f():

t = threading.Thread(target=f)
print("main ending")

That prints:

going away
main ending

and then it hangs forever, as Python attempts to .join() the thread as part of interpreter shutdown processing.

The function f(), run in a thread, creates an instance of C that becomes trash immediately after its e attribute is retrieved. So its __del__ method is called, and "going away" is displayed.

You can infer from the behavior that, no, a trash Event does not get set by magic. But it's not going to come up in practice, so don't worry about it ;-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download