了解python线程错误

了解python线程错误,python,python-multithreading,Python,Python Multithreading,通过阅读,我可以看到Stephen White编写的一个简单脚本,它演示了python线程如何处理这个异常 Exception AttributeError: AttributeError("'_DummyThread' object has no attribute '_Thread__block'",) in <module 'threading' 我们如何重新编写它以解决此错误?发生的原因是,当调用外部线程上的threading.currentThread()和threading

通过阅读,我可以看到Stephen White编写的一个简单脚本,它演示了python线程如何处理这个异常

Exception AttributeError: AttributeError("'_DummyThread' object has no attribute '_Thread__block'",) in <module 'threading' 
我们如何重新编写它以解决此错误?

发生的原因是,当调用外部线程上的
threading.currentThread()
threading.\u after\u fork
函数时,由
threading
API创建的虚拟线程对象之间的交互不好,调用以在调用
os.fork()
后清理资源

要在不修改Python源代码的情况下解决此错误,请使用monkey patch
threading.\u DummyThread
,并使用
\u stop
的无操作实现:

import threading
threading._DummyThread._Thread__stop = lambda x: 42
错误的原因最好在和的注释中缩小。发生的情况如下:

  • threading
    模块允许从不是由
    threading
    API调用创建的线程调用
    threading.currentThread()
    。然后,它返回一个“虚拟线程”实例,该实例支持非常有限的
    thread
    API子集,但仍然有助于识别当前线程

  • threading.\u DummyThread
    作为
    Thread
    的子类实现<代码>线程实例通常包含一个内部可调用(
    self.\u块
    ),它保留对为实例分配的操作系统级锁的引用。由于公共
    线程
    方法可能最终使用
    self.\uu block
    都被
    \u DummyThread
    覆盖,
    \u DummyThread
    的构造函数通过删除
    self.\uu block
    故意释放操作系统级锁

  • threading.\u fork
    之后会破坏封装并调用私有的
    线程。\uu stop
    方法用于所有注册的线程,包括虚拟线程,其中
    \uu stop
    从未被调用。(它们不是由Python启动的,因此它们的停止也不是由Python管理的。)由于虚拟线程不知道
    \u stop
    ,它们从
    线程继承它,并且该实现愉快地访问
    \u DummyThread
    实例中不存在的私有
    \u块
    属性。此访问最终导致错误


  • 当删除
    \u块
    时,2.7分支中的错误被修复。3.x分支,其中
    \u stop
    拼写为
    \u stop
    ,因此受到保护,修复了它。

    在我看来,您可以将其全部重写为
    time.sleep(3)
    。我认为您应该指定重写的程序实际应该做什么。@JanneKarila该程序只是演示了一个Python bug,如果您在Python 2.7中运行它,您将看到它。请求是在不升级到修复它的Python版本的情况下解决这个bug。啊。。。我现在明白了。。。谢谢
    import threading
    threading._DummyThread._Thread__stop = lambda x: 42