gpt4 book ai didi

python - 导入默默地杀死线程

转载 作者:行者123 更新时间:2023-11-30 22:29:38 25 4
gpt4 key购买 nike

我有一个简单的程序Base.py,它测试当模块不存在时import是否能够抛出异常。

# Base.py
import threading, os, time
import_is_working = False

class Launch(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
global import_is_working
try:
print "Yes, it got into the 'try' block"
import NON_EXISTENT_MODULE
assert False
except:
print "Great, your python language is working"
import_is_working = True
Launch()
for i in range(500):
time.sleep(0.01)
if import_is_working:
break
if not import_is_working:
print "Your import is not working."
os._exit(4)

有时我喜欢在另一个模块中使用此代码Main.py:

# Main.py
import Base

令人惊讶的是,当我这样运行时它不起作用:

max% python Base.py
Yes, it got into the 'try' block
Great, your python language is working
max% python Main.py
Yes, it got into the 'try' block
Your import is not working.
max%

这会发生在 Ubuntu 中,在干净的 CentOS 7.3 安装中也会发生。

最佳答案

您遇到了“导入锁”。

documentation提到了在线程期间导入的限制,您违反了第一个(强调我的):

While the import machinery is thread-safe, there are two key restrictions on threaded imports due to inherent limitations in the way that thread-safety is provided:

Firstly, 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.

Secondly, all import attempts must be completed before the interpreter starts shutting itself down. This can be most easily achieved by only performing imports from non-daemon threads created through the threading module. Daemon threads and threads created directly with the thread module will require some other form of synchronization to ensure they do not attempt imports after system shutdown has commenced. Failure to abide by this restriction will lead to intermittent exceptions and crashes during interpreter shutdown (as the late imports attempt to access machinery which is no longer in a valid state).

关于python - 导入默默地杀死线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46290045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com