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

4

1 回答 1

2

你没有setDaemon()正确使用。结果,没有一个Downloader线程是守护线程。

代替

thread.setDaemon = True

thread.setDaemon(True)

或者

thread.daemon = True

文档似乎暗示后者是 Python 2.6+ 中的首选拼写。)

于 2013-10-24T11:51:02.493 回答