2017-10-09 94 views
1

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

+0

難道你不想加入while循環嗎? –

+0

使用循環或列表理解來過濾不再活動的線程 –

+1

您可能希望創建一個固定的線程池(ThreadPool)並在它們之間共享工作,而不是爲每個'x'創建一個新線程。 – 101

回答

0

最後行(for -loop和上)可以寫成是簡單的如:

threads_alive = [] 
    for t in threads: 
     if t.is_alive() == False: 
      t.join() 
     else: 
      threads_alive.append(t) 

    threads = threads_alive 

,或者如果你有處理已經死線程不知何故尚未:

threads_alive = [] 
    threads_dead = [] 
    for t in threads: 
     if t.is_alive() == False: 
      t.join() 
      threads_dead.append(t) 
     else: 
      threads_alive.append(t) 

    threads = threads_alive 
    for t in threads_dead: 
     ... postprocess dead threads here ... 
+0

我通過枚舉存儲了死亡線程,因爲我需要將它從列表中刪除,但我的解決方案或多或少是相同的。謝謝! – r0edie