线程融化了我的大脑。我已经看到了几种不同的方法来实现 worker + keepalive 模型,但是很难找出最好的方法。这是代码的简化版本:
def start_thread(function):
t = Thread(target=function)
t.setDaemon(True)
t.start()
def worker:
run = True
start_thread(keepalive_fn)
msg = recv() #blocking
while msg is not None and run:
process(msg)
try:
msg = recv()
except:
if run:
reconnect()
break
else:
if run:
reconnect()
def keepalive_fn():
while run:
try:
send('hb')
except:
close_connection()
break
sleep(heartbeat)
def connect():
open_connection()
start_thread(worker)
def reconnect():
close_connection()
connect()
connect()
这会像宣传的那样工作吗?有没有更好的办法?请注意,调用 close_connection() 时没有损坏的消息,因为 recv() 已经处理了这种情况。