我最好从代码中开始提问。
from multiprocessing import Process, Event, Queue
from threading import Timer
from Queue import Empty
class MyServer(Process):
def __init__(self, port, queue):
Process.__init__(self)
self.port = port
self.queue = queue
self.sd = None
def run(self):
try:
self.start_serving()
except KeyboardInterrupt:
print("Shutting down..")
finally:
if self.sd is not None:
self.sd.close()
def start_serving(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sd = s
try:
s.bind(('', self.port))
s.listen(1)
while True:
conn, addr = s.accept()
while True:
# I dont want to bore you with excess code
# just recv data from clients
try:
msg = self.queue.get_nowait()
# here i start Timer with delay from message (I'll describe Message class below)
Timer(msg.delay, self.response_handler, args=(conn, msg)).start()
except Empty:
pass
conn.close()
finally:
s.close()
def response_handler(self, sd, msg):
# doesn't matter
# and now I want to terminate the MyServer instance
if msg.terminate:
# the problem is here. Lets call it 'problem line'
sys.exit()
msg
是Message
类的实例,它是:
class Message(object):
def __init__(self, port, delay, values, terminate=False):
self.port = port
self.delay = delay
self.values = values
self.terminate = terminate
逻辑是我通过TCP连接从客户端获取数据并检查队列中的消息。消息是控制服务器的东西。有时候我会收到“等待3秒并终止服务器”的消息。 到目前为止我做了什么。
self.terminate()
致电problem line
。我明白了
AttributeError: 'NoneType' object has no attribute 'terminate'
problem line
处提出异常。我假设异常是在run()
函数中捕获的。我曾是
错sys.exit()
。它也不起作用。也许我的问题可以缩短。如何从Python中的线程终止进程?
答案 0 :(得分:2)
为什么不使用multiprocessing.Event
(您已经导入它)并在收到终止消息时正常退出流程。
为此,请将其添加到__init__
:
self.exit = Event()
并更改两个while
循环:
while True:
conn, addr = s.accept()
while True:
#...
到
while not self.exit.is_set():
conn, addr = s.accept()
while not self.exit.is_set()
#...
然后在你的响应处理程序中:
if msg.terminate:
self.exit.set()
这将允许代码自然地退出循环,确保调用conn.close()
。