Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何用线程正确结束程序?_Python_Multithreading - Fatal编程技术网

Python 如何用线程正确结束程序?

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

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

出于某种原因,该程序不希望正常结束

代码如下:

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