2
我有一個類從隊列中拉出項目,然後在其上運行代碼。我還在主函數中添加了將項目添加到隊列進行處理的代碼。如何使用線程正確結束程序?
由於某種原因,程序不想正常結束。
下面是代碼:
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
循環,但我認爲設置線程爲守護進程就是爲了解決這個問題。
'while True'w生病無限地運行,它應該停止,然後線程將終止。 – andrean