2017-10-09 135 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