我发现这篇关于Python中队列的文章:http://www.blog.pythonlibrary.org/2012/08/01/python-concurrency-an-example-of-a-queue/
它工作正常,但我对此有疑问。在线程的run方法中我们看到:
def run(self):
while True:
# gets the url from the queue
url = self.queue.get()
# download the file
self.download_file(url)
# send a signal to the queue that the job is done
self.queue.task_done()
线程处于无限 while 循环中,没有调用break。当程序结束时这个线程会发生什么?
最佳答案
这取决于你所说的“程序结束”是什么意思。如果主线程刚刚执行结束,有两种可能:
如果线程是非守护进程
threading.Thread
,则正在运行的线程将使程序无限期地保持事件状态。如果线程是守护进程,则一旦主线程结束,该线程就会突然终止。
daemon
属性在文档中的描述如下:
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when no alive non-daemon threads are left.
如果“程序结束”是指进程收到 SIGTERM 或 SIGKILL 或类似的信号,那么线程将与程序的其余部分一起终止,即使它不是守护进程
。
关于python - 如果线程处于无限 while 循环中,会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26143318/