Эй, недавно нашёл ещё один способ. Можно использовать concurrent.futures:
Программный код:
from concurrent.futures import ThreadPoolExecutor
import time
def worker(stop_event):
while not stop_event.is_set():
print('Working...')
time.sleep(1)
stop_event = threading.Event()
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(worker, stop_event)
time.sleep(5)
stop_event.set()
future.result()
print('Thread stopped')
Через executor управлять потоками - вообще огонь, легко масштабируется.