2013-10-24 83 views
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循環,但我認爲設置線程爲守護進程就是爲了解決這個問題。

+0

'while True'w生病無限地運行,它應該停止,然後線程將終止。 – andrean

回答

2

您沒有正確使用setDaemon()。因此,Downloader線程都不是守護進程線程。

代替

thread.setDaemon = True 

寫入

thread.setDaemon(True) 

thread.daemon = True 

The docs似乎意味着後者是在Python優選拼寫2.6+。)

+0

謝謝你。它現在工作:) – Leinad177