python - 如果线程处于无限 while 循环中,会发生什么情况?

标签 python multithreading blockingqueue

我发现这篇关于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。当程序结束时这个线程会发生什么?

最佳答案

这取决于你所说的“程序结束”是什么意思。如果主线程刚刚执行结束,有两种可能:

  1. 如果线程是非守护进程threading.Thread,则正在运行的线程将使程序无限期地保持事件状态。

  2. 如果线程是守护进程,则一旦主线程结束,该线程就会突然终止。

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/

相关文章:

java - 使用 SynchronousQueue 解决消费者生产者并发问题。公平属性不起作用

java - 阻塞队列和多线程消费者,如何知道何时停止

python - 计算 DataFrame 列中标点符号的数量

python - Selenium 中的剪贴板按钮

python - ubuntu 16.04.3 中的哈希和不匹配

c# - 调试期间的线程

python - 如何处理 "inspect.getsource"的限制 - 或者如何仅获取函数的源代码?

c++ - 在不同线程之间通过 (c++) openmp 共享信息

c# - pjsip c#,在单独线程上应答传入调用时出现 System.AccessViolationException

java - 我可以在Java中用两个对象作为锁来实现阻塞队列吗?