import gc import threading import time import uuid procs = [] def _target(): time.sleep(5) some_data = bytearray(3145728) time.sleep(5) def _create_thread(): process = threading.Thread(target=_target, name=str(uuid.uuid4())) process.start() procs.append(process) def _cleanup_processes(): for proc in procs: if proc.is_alive(): continue proc.join() procs.remove(proc) print("Creating threads...") for i in range(1,20): _create_thread() time.sleep(3) # when commenting this out it doesn't leak anymore print("DONE!\n") print("Creating more threads...") for i in range(1,20): _create_thread() print("DONE!\n") print("Sleeping for 30 seconds. Letting the threads to finish their job...") time.sleep(30) print("woke up again!\n") while True: print("Running garbage collector. ") gc.collect() print("DONE.\n") print("Cleaning up processes...") _cleanup_processes() print("# of processes left: {}", len(procs)) print("DONE.\n") print("Sleeping a bit...") time.sleep(3) print("DONE!\n")