Reputation: 3101
this thread discusses at great length why it is not a good idea to kill threads. And I agree when we are talking about an actual program.
I am writing unit tests for several components as well as some integration tests between them. Some require threading. When tests fail, some threads stay open, locked in a .get()
call of a queue. This causes the whole test suite to get stuck and not complete. I am running either ptw
(pytest watch) or a custom loop of pytest with inotifywait
to watch for changes in my files to rerun the suite.
When all tests have completed, I want the suite to kill any remaining threads to complete the loop and not be stuck on a thread somewhere that is just open because of a test failure. Is this possible?
Upvotes: 8
Views: 4494
Reputation: 27
Based on Sraw's response, I was able to set the thread to terminate when the main thread terminates, passing daemon=True when starting the thread:
threading.Thread(target=method, daemon=True).start()
So when I run my unit tests, for example, it would end the execution instead of keep running forever since there's still a thread running.
Upvotes: 2
Reputation: 20206
There isn't an elegant way to stop a thread, but you can set their daemon
to True
.
code snippet:
import threading
all_child_threads = [thread for thread in threading.enumerate() if thread != threading.main_thread()]
for thread in all_child_threads:
thread.daemon = True
Then they will terminate when main thread terminates.
Upvotes: 8