I have been looking for some time for a solution to terminate a socketserver.StreamRequestHandler
spawned as a separate thread by the class ThreadingMixIn
when the main tread terminates. The problem was that the socketserver thread, although being daemonic, would not terminate as long as there was an open client connection, even when calling its shutdown()
method at program shutdown. Therefore, the main tread also did not terminate. None of the suggestions in How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass? or similar posts worked for me.
I have now found a solution:
The class ThreadingMixIn
has a property daemonic_threads
, which is by default true:
class ThreadingMixIn:
"""Mix-in class to handle each request in a new thread."""
# Decides how threads will act upon termination of the
# main process
daemon_threads = False
In my subclass, which, of course, overrides the method handle()
, I now also defines override in __init__
:
daemon_threads = True
Now all client requests are daemonic and when the main thread terminates, they also terminate. Nice ! Hopefully this helps someone with a similar problem.