python – 导入静默杀死线程
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 导入静默杀死线程,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2059字,纯文字阅读大概需要3分钟。
内容图文
![python – 导入静默杀死线程](/upload/InfoBanner/zyjiaocheng/710/5558b31975da456b8973ceaf85cea3fc.jpg)
我有一个简单的程序Base.py,它测试导入是否能够在模块不存在时抛出异常.
# 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 – 导入静默杀死线程全部内容,希望文章能够帮你解决python – 导入静默杀死线程所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。