7

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?

pascalwhoop
  • 2,984
  • 3
  • 26
  • 40

2 Answers2

6

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.

Sraw
  • 18,892
  • 11
  • 54
  • 87
  • This could work, however I wouldn't exactly know where to place it. Theoretically, I could put it into every `tearDownClass` of all classes that use threading in my tests but a global hook would be nicer. – pascalwhoop Jun 15 '18 at 08:17
  • Isn't it another question? What only I can help you about it: https://docs.pytest.org/en/latest/fixture.html#fixture-finalization-executing-teardown-code – Sraw Jun 15 '18 at 09:20
2

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.

karthikeayan
  • 4,291
  • 7
  • 37
  • 75
Bipe
  • 27
  • 5