我有一个从队列中提取项目然后在其上运行代码的类。我在主函数中也有代码,可以将项目添加到队列中进行处理。
出于某种原因,程序不想正常结束。
这是代码:
class Downloader(Thread):
def __init__(self, queue):
self.queue = queue
Thread.__init__(self)
def run(self):
while True:
download_file(self.queue.get())
self.queue.task_done()
def spawn_threads(Class, amount):
for t in xrange(amount):
thread = Class(queue)
thread.setDaemon = True
thread.start()
if __name__ == "__main__":
spawn_threads(Downloader, 20)
for item in items: queue.put(item)
#not the real code, but simplied because it isn't relevant
print 'Done scanning. Waiting for downloads to finish.'
queue.join()
print 'Done!'
该程序等待它正确完成queue.join()
并打印Done!
,但是有些东西使程序无法关闭,我似乎无法理解。我认为这是while True
循环,但我认为将线程设置为守护进程是为了解决这个问题。