我正在编写一个应该无限期运行的脚本,并且每隔几秒就使用线程将一些东西放在db中。这种方式很有效,但是我看到进程的内存每隔几秒就会略微增加,我认为这是因为保存所有线程对象的列表永远不会被清空。我会怎么做? 连接被置于is_alive条件下,所以它不会花费任何时间来产生下一个线程。 下面的例子导致一个python3如何从列表中删除线程对象
AttributeError: 'Thread' object has no attribute 'kill'
import threading
import time
def dicthing(dic, x):
dic.update({x: x*x})
time.sleep(0.01)
dic = {}
threads = []
x = 100
while x > 0:
t = threading.Thread(target = dicthing, args = (dic, x))
threads.append(t)
t.start()
x -= 1
if x % 50 == 0:
print(len(threads), len(threading.enumerate()))
for t in threads:
if t.is_alive() == False:
t.join()
t.kill = True
threads = [t for t in threads if not t.kill]
我想输出是:
1 1
1 1
难道你不想加入while循环吗? –
使用循环或列表理解来过滤不再活动的线程 –
您可能希望创建一个固定的线程池(ThreadPool)并在它们之间共享工作,而不是为每个'x'创建一个新线程。 – 101