python - 线程在 Python 中随机停止

标签 python multithreading

我一直在玩 Python 中的线程,我发现了一些有趣的代码:

import time
import threading

class Update(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
    self.stop_event = threading.Event()

  def join(self, timeout=None):
    self.stop_event.set()
    threading.Thread.join(self, timeout)

  def run(self):
    while not self.stop_event.isSet():
      print("test")

thread = Update()
thread.start()

即使我不调用 join() 方法,这段代码也会随机停止。结果,我得到了如下不同的输出:

test@debian:~/$ python3 test.py
test
test
test
test
test@debian:~/$ python3 test.py
test
test
test
test
test
test
test
test@debian:~/$ python3 test.py
test
test

为什么这段代码会随机停止?我以为只有设置stop_event这个线程才会停止。

最佳答案

你已经得到了基本的答案,但有一个细节你需要注意:当主程序结束时,作为关闭处理的一部分,Python 在所有非守护进程上调用 .join() threading 模块创建的线程。您覆盖了 .join(),因此 Python 调用您的 .join()。这反过来会设置事件,因此您的 .run() 方法会静默退出。

关于python - 线程在 Python 中随机停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36699899/

相关文章:

python - 轨迹栏回调python openCV

iphone - NSFetchedResultsController 委托(delegate)和后台驱动的更新

multithreading - Delphi:PostThreadMessage和PeekMessage不起作用

python - 渲染模板并将数据插入本地存储

vb.net - VB Net - 将数据从线程传递到主 GUI

ios - Xcode 5 调试 - CPU 报告/使用情况中的 "Unnamed"线程

java - 布赖恩·戈茨 : SafePoint example - is it really thread-safe?

python - 检查h5py中是否存在节点

Python函数出现异常时返回1

python - 如何在不提取的情况下遍历包含 zip 文件的 tar.gz 文件