为了证明线程在作业完成后被销毁,可以运行以下代码:def job(o: dict):
count = 1
r = random.randrange(10, 20)
while count < r:
print(f"{o['name']}={count}/{r}")
count += 1
time.sleep(1)
print(f"{o['name']} finished.")
def run_thread(o: dict):
threading.Thread(target=job, args=(o,)).start()
if __name__ == '__main__':
obj1 = {"name": "A"}
run_thread(obj1)
obj2 = {"name": "B"}
run_thread(obj2)
while True:
time.sleep(1)
print(f"THREADS: {len(threading.enumerate())}")
输出如下:
^{pr2}$
如您所见,每当一个线程结束时,总线程数就会减少。在
更新:
好吧。我希望这个剧本能让你满意。在from typing import List
import random
import threading
import time
import os
import psutil
def get_mem_