星期四, 七月 26, 2007

python main process when raise in child thread?

如果是使用 forking,子进程异常退出应该不会影响到父进程的运行。而对于线程来说,地址空间是和主线程共享的,那么在子线程中产生的异常会不会影响到主线程的运行呢。编写一段代码测试之:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import threading

class Exc:
def __init__(self, msg): self.msg = msg

def run_thread():
raise Exc("rasie Exception in child thread")

st = threading.Thread(target=run_thread, name="child")
st.setDaemon(1)
st.start()
st.join()
print "Main Process End"

sh$ python threading_test.py
Exception in thread child:
Traceback (most recent call last):
File "/usr/lib/python2.5/threading.py", line 460, in __bootstrap
self.run()
File "/usr/lib/python2.5/threading.py", line 440, in run
self.__target(*self.__args, **self.__kwargs)
File "threading_test.py", line 10, in run_thread
raise Exc("rasie Exception in child thread")
Exc: <__main__.exc>

Main Process End
最后 Main Thread 仍然打印了 "Main Process End",说明主线程没有受到影响。

没有评论: