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?