两种解决方案:
1)不要停止线程,只允许它在进程退出时终止sys.exit()
2)以“立即模具”标志启动线程。Event类是专门为从另一个线程发出信号而设计的。在
下面的示例启动一个线程,该线程连接到服务器。任何数据都会被处理,如果父进程向线程发出退出的信号,它就会。作为一个附加的安全功能,我们有一个报警信号来杀死所有的东西,只是万一事情失控。在
来源import signal, socket, threading
class MyThread(threading.Thread):
def __init__(self, conn, event):
super(MyThread,self).__init__()
self.conn = conn
self.event = event
def handle_data(self):
"process data if any"
try:
data = self.conn.recv(4096)
if data:
print 'data:',data,len(data)
except socket.timeout:
print '(timeout)'
def run(self):
self.conn.settimeout(1.0)
# exit on signal from caller
while not self.event.is_set():
# handle any data; continue loop after 1 second
self.handle_data()
print 'got event; returning to caller'
sock = socket.create_connection( ('example.com', 80) )
event = threading.Event()
# connect to server and start connection handler
th = MyThread(conn=sock, event=event)
# watchdog: kill everything in 3 seconds
signal.alarm(3)
# after 2 seconds, tell data thread to exit
threading.Timer(2.0, event.set).start()
# start data thread and wait for it
th.start()
th.join()
输出
^{pr2}$