Skip to main content
 首页 » 编程设计

python之为什么在 python 队列消耗完所有工作后不释放线程

2025年05月04日12kenshinobiy

我使用 Queue 来提供线程可以处理的任务。从 Queue 完成所有工作后,我看到线程仍然存在,而我预计它们会被释放。这是我的代码。在控制台中一批任务(在同一队列中)增加后,您可以看到事件线程数正在增加。如何在完成一批工作后释放线程?

import threading 
import time 
from Queue import Queue 
 
class ThreadWorker(threading.Thread): 
    def __init__(self, task_queue): 
        threading.Thread.__init__(self) 
        self.task_queue = task_queue 
 
    def run(self): 
        while True: 
            work = self.task_queue.get() 
            #do some work 
            # do_work(work) 
            time.sleep(0.1) 
            self.task_queue.task_done() 
 
def get_batch_work_done(works): 
    task_queue =  Queue() 
    for _ in range(5): 
        t = ThreadWorker(task_queue) 
        t.setDaemon(True) 
        t.start() 
    for work in range(works): 
       task_queue.put(work) 
    task_queue.join() 
    print 'get batch work done' 
    print 'active threads count is {}'.format(threading.activeCount()) 
 
if __name__ == '__main__': 
    for work_number in range(3): 
        print 'start with {}'.format(work_number) 
        get_batch_work_done(work_number) 

请您参考如下方法:

在循环中做一个非阻塞读并使用异常处理终止

def run(self): 
      try:             
        while True:             
          work = self.task_queue.get(True, 0.1) 
        #do some work 
        # do_work(work) 
      except Queue.Empty: 
        print "goodbye"