WhiskeyAndRye WhiskeyAndRye - 5 months ago 11
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

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

I'm new to asynchronicity, so if event's don't
set()
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

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():
    C().e.wait()

t = threading.Thread(target=f)
t.start()
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 ;-)

Comments