Python 如何用线程正确结束程序?
我有一个类,它从队列中提取项目,然后在队列上运行代码。我在main函数中也有代码,可以将项目添加到队列中进行处理 出于某种原因,该程序不希望正常结束 代码如下:Python 如何用线程正确结束程序?,python,multithreading,Python,Multithreading,我有一个类,它从队列中提取项目,然后在队列上运行代码。我在main函数中也有代码,可以将项目添加到队列中进行处理 出于某种原因,该程序不希望正常结束 代码如下: class Downloader(Thread): def __init__(self, queue): self.queue = queue Thread.__init__(self) def run(self): while True: d
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!'
程序在队列中等待它正确完成。join()
并打印完成代码>,但有些东西阻止程序关闭,我似乎无法确定。我假设这是while True
循环,但我认为将线程设置为守护进程就是为了解决这个问题。您没有正确地使用。因此,下载程序
线程都不是守护进程线程
而不是
thread.setDaemon = True
写
或
(似乎意味着后者是Python 2.6+中的首选拼写)。虽然True
将无限期地运行,但它应该停止,然后线程将终止。
thread.setDaemon(True)
thread.daemon = True