导入时生成新线程 [英] Spawning a new thread while importing

查看:190
本文介绍了导入时生成新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的 threading 文档状态:

Python's threading documentation states:


除了在主模块中,导入不应该有$ b边$ b产生一个新线程的效果,然后以
的任何方式等待该线程。如果生成的线程直接或间接尝试导入
模块,则不遵守此限制可能导致死锁

Other than in the main module, an import should not have the side effect of spawning a new thread and then waiting for that thread in any way. Failing to abide by this restriction can lead to a deadlock if the spawned thread directly or indirectly attempts to import a module.

我正在寻找演示此限制的示例代码。

I'm looking for example code that demonstrates this restriction.

推荐答案

我试过这个,一个产生的模块一个线程,其目标试图从线程导入线程导入 sys

I tried this, a module that spawns a thread whose target tries to import sys:

from threading import Thread

def my_target():
    import sys

thread = Thread(target=my_target)
thread.start()
thread.join()

当启动python解释器并尝试导入上面的模块时,它确实冻结了。

When the python interpreter is launched and an attempt to import the module above is made, it indeed freezes.

这篇关于导入时生成新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆