gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:54:36 25 4
gpt4 key购买 nike

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

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

代码如下:

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+ 中的首选拼写。)

关于python - 如何用线程正确结束一个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19565065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com