【问题标题】:Spawning a new thread while importing导入时产生一个新线程
【发布时间】:2011-12-10 20:19:09
【问题描述】:

Python 的 threading documentation 声明:

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

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

【问题讨论】:

  • 这不是因为模块导入通常不是线程安全的吗?
  • @DanD。 - 实际上文档也说:While the import machinery is thread-safe, there are two key restrictions on threaded imports due to inherent limitations...
  • threading 重新导入有两个限制 - 我问了一个相关问题 here

标签: python multithreading import restriction


【解决方案1】:

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

from threading import Thread

def my_target():
    import sys

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

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

【讨论】:

    猜你喜欢
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多