This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Sergei Maertens
Recipients Sergei Maertens, asvetlov, bquinlan, erickpeirson, pitrou, serhiy.storchaka, yselivanov
Date 2021-12-14.20:58:48
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1639515528.79.0.621874339094.issue45339@roundup.psfhosted.org>
In-reply-to
Content
I was looking for some way to be able to add a thread finalizer, a piece of code to be called when the thread pool shuts down and all threads need cleaning up. Glad I came across this issue, since the example of using a Thread subclass with a custom run (wrapped in a context manager) would fill my needs completely.

> What are examples of your some_important_context()? Is it important to call some code before destroying the thread?

I currently have a use case with a web-framework that has persistent DB connections - i.e. they span multiple HTTP requests. This also applies in the context of running a command-line script with said framework where database connections are opened.

We are calling external APIs (IO heavy), so using a ThreadPoolExecutor makes sense. However, since those "DB connection pools" are thread locals, we need to ensure that database connections are closed again to not leak resources.

The current workaround is to submit a job/function to the pool and have it close the database connections, which adds overhead since database connections are now opened and closed within the same thread that could have been re-used.

Using a context manager, we would be able to wrap the `super().run(...)` and close the database connections when the thread exits (succesfully or because of an Exception, even). This comes very close to having an `atexit` for individual threads.

Furthermore I like the idea of being able to provide the class as a context manager kwarg, but would also not be opposed to a class property specifying the Thread class to use - both would greatly enhance composability and are a cleaner solution than adding a finalizer option (similar to the `initializer` kwarg)
History
Date User Action Args
2021-12-14 20:58:48Sergei Maertenssetrecipients: + Sergei Maertens, bquinlan, pitrou, asvetlov, serhiy.storchaka, yselivanov, erickpeirson
2021-12-14 20:58:48Sergei Maertenssetmessageid: <1639515528.79.0.621874339094.issue45339@roundup.psfhosted.org>
2021-12-14 20:58:48Sergei Maertenslinkissue45339 messages
2021-12-14 20:58:48Sergei Maertenscreate