Sergei Maertens <sergeimaert...@gmail.com> added the comment:

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)

----------
nosy: +Sergei Maertens

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue45339>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to