For example, there is a code:

import threading from time import sleep class MyThread(threading.Thread): def __init__(self, key): super(MyThread, self).__init__() self.daemon = True self.key = key self.start() def run(self): while True: print('thread', self.key) sleep(1.5) threads = dict() def add_thread(key): key = int(key) if threads.get(key) is None: threads[key] = MyThread(key) def del_thread(key): key = int(key) if threads.get(key) is not None: thread = threads.pop(key, None) if thread is not None: # тут, что-то, что освободит поток print('остановка', key) i = 0 while True: add_thread(i) i += 1 if i >= 10: del_thread(i - 10) sleep(1) 

Code dynamically add threads, but you also need to dynamically and stop them, how to do it in this example?

    1 answer 1

    Replace while True: with while not self.stopped.wait(1.5):.. (remove time.sleep(1.5) ), where self.stopped = threading.Event() , then to stop the flow, call thread.stopped.set() (the thread will be released on the wait() call, without waiting for 1.5 seconds to end).

    The code in question can be simplified: to start a new stream every second and stop it after ten iterations:

     #!/usr/bin/env python3 import collections import logging import time import threading def worker(stopped): while not stopped.wait(1.5): logging.info("heartbeat") logging.basicConfig(level=logging.INFO, format="%(relativeCreated)d %(threadName)s %(message)s") events = collections.deque(maxlen=10) while True: events.append(threading.Event()) threading.Thread(target=worker, args=[events[-1]], daemon=True).start() if len(events) == 10: events.popleft().set() # stop 10th thread from the end time.sleep(1 - time.monotonic() % 1) # every second 

    For details on this time.sleep() call, see. How to make a temporary loop correctly?