Skip to main content
 首页 » 编程设计

python之如何用线程正确结束一个程序

2024年11月01日10itcoder

我有一个类可以从队列中提取项目,然后在其上运行代码。我在主函数中也有代码将项目添加到队列中进行处理。

由于某种原因,程序不想正常结束。

代码如下:

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 循环,但我认为将线程设置为守护进程是为了解决这个问题。

请您参考如下方法:

您没有使用 setDaemon()正确。因此,Downloader 线程都不是守护线程。

代替

thread.setDaemon = True 

写

thread.setDaemon(True) 

或

thread.daemon = True 

(The docs 似乎暗示后者是 Python 2.6+ 中的首选拼写。)