我们遇到了这个错误:
http://bugs.python.org/issue1856守护程序线程在解释器关闭期间segfault。
现在我搜索一种方法来围绕这个bug进行编码。
目前代码如下:
while True:
do_something()
time.sleep(interval)
有没有办法在do_something()之前检查解释器是否仍然可用?
还是最好不要执行mythread.setDaemon(True)和检查主线程是否已退出?
回答自己的问题:
我现在使用这个模式:不要设置Daemon(True),不要使用sleep(),使用parent_thread.join()
while True:
parent_thread.join(interval)
if not parent_thread.is_alive():
break
do_something()
相关:http://docs.python.org/2/library/threading.html#threading.Thread.join
这是线程处理的代码。py模块:
import sys as _sys
class Thread(_Verbose):
def _bootstrap_inner(self):
# some code
# If sys.stderr is no more (most likely from interpreter
# shutdown) use self._stderr. Otherwise still use sys (as in
# _sys) in case sys.stderr was redefined since the creation of
# self.
if _sys:
_sys.stderr.write("Exception in thread %s:n%sn" %
(self.name, _format_exc()))
else:
# some code
可能会有所帮助。您看到的错误来自else
语句。所以在你的情况下:
import sys as _sys
while True:
if not _sys:
break/return/die/whatever
do_something()
time.sleep(interval)
不过,我不确定它是否有效(请注意,解释器关闭可能发生在do_something
内部,因此您可能应该用try:except:
包装所有内容)。
守护程序线程不一定是坏的,它们肯定可以加快开发过程。你只需要小心对待他们。