[英]Why doesn't this async code stop?
以下代码段分别具有两个协程,分别用于服务器和客户端。 客户端协程具有在10秒后中断while
循环的逻辑,服务器应在15秒后停止。
当我运行脚本时,它不会停止,理想情况下,它应该在15秒后停止,但这不会发生。
import asyncio
import time
import zmq
import zmq.asyncio
zmq.asyncio.install()
ctx = zmq.asyncio.Context()
server_socket = ctx.socket(zmq.REP)
client_socket = ctx.socket(zmq.REQ)
server_socket.bind("tcp://127.0.0.1:8899")
client_socket.connect("tcp://127.0.0.1:8899")
t0 = time.time()
@asyncio.coroutine
def server_coroutine():
while True:
msg = yield from server_socket.recv_string()
print(msg)
msg = "Server:: {}".format(msg)
yield from server_socket.send_string(msg)
t1 = time.time()
elapsed_time = t1 - t0
# print('elapsed time is {}'.format(elapsed_time))
if elapsed_time > 15:
print("Breaking Server loop")
break
@asyncio.coroutine
def client_coroutine():
counter = 0
while True:
yield from asyncio.sleep(2)
msg = 'Message: {}'.format(counter)
yield from client_socket.send_string(msg)
res = yield from client_socket.recv_string()
print(res)
t1 = time.time()
elapsed_time = t1 - t0
print('elapsed time is {}'.format(elapsed_time))
if elapsed_time > 10:
print("Breaking Client loop")
break
counter += 1
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(
asyncio.ensure_future(server_coroutine()),
asyncio.ensure_future(client_coroutine())
))
如果您运行代码,您将看到类似以下内容:
Server:: Message: 4
elapsed time is 10.022311687469482
Breaking Client loop
好的, client_coroutine
成功完成,但是此时server_coroutine
处于什么状态? 它停留在此行msg = yield from server_socket.recv_string()
等待从server_socket
字符串的可能性,但是不会发生,因为已经没有客户端可以发送它了! 而且由于您的事件循环一直运行到两个协程完成,所以它将永远运行。
这是最简单的解决方法:
@asyncio.coroutine
def server_coroutine():
while True:
msg = yield from server_socket.recv_string()
if msg == 'CLOSE': # LOOK HERE 1
break
print(msg)
msg = "Server:: {}".format(msg)
yield from server_socket.send_string(msg)
t1 = time.time()
elapsed_time = t1 - t0
# print('elapsed time is {}'.format(elapsed_time))
if elapsed_time > 15:
print("Breaking Server loop")
break
@asyncio.coroutine
def client_coroutine():
counter = 0
while True:
yield from asyncio.sleep(2)
msg = 'Message: {}'.format(counter)
yield from client_socket.send_string(msg)
res = yield from client_socket.recv_string()
print(res)
t1 = time.time()
elapsed_time = t1 - t0
print('elapsed time is {}'.format(elapsed_time))
if elapsed_time > 10:
print("Breaking Client loop")
yield from client_socket.send_string('CLOSE') # LOOK HERE 2
break
counter += 1
请注意,此修复程序仅用于演示问题以及解决该问题的一种可能方法。
在现实生活中,我认为您可能会想做一些不同的事情:可能会为协程设置超时,以确保如果客户端/服务器停止响应,协程不会永远卡住。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.