我正在編寫一個應該無限期運行的腳本,並且每隔幾秒就使用線程將一些東西放在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