我正在尝试熟悉asyncio,因此我决定编写一个数据库客户端。然而,性能与同步代码完全相同。我确信这是我的某个概念误解。能否有人解释一下我做错了什么?
请参见以下代码示例:
class Connection:
def __init__(self, reader, writer, loop):
self.futures = deque()
# ...
self.reader_task = asyncio.async(self.recv_data(), loop=self.loop)
@asyncio.coroutine
def recv_data(self):
while 1:
try:
response = yield from self.reader.readexactly(4)
size, = struct.unpack('I', response)
response = yield from self.reader.readexactly(size)
# ...
future = self.futures.popleft()
if not future.cancelled():
future.set_result(response)
except Exception:
break
def send_data(self, data):
future = asyncio.Future(loop=self.loop)
self.futures.append(future)
self.writer.write(data)
return future
loop = asyncio.get_event_loop()
@asyncio.coroutine
def benchmark():
connection = yield from create_connection(loop=loop, ...)
for i in range(10000):
yield from connection.send_data(...)
s = time.monotonic()
loop.run_until_complete(benchmark())
e = time.monotonic()
print('Requests per second:', int(10000 / (e - s)))
提前致谢。
asyncio.wait
将包装任何传递进来的协程对象或可等待对象到一个Task
未来对象中。自己使用loop.create_task
或asyncio.ensure_future
进行包装可能会在循环中安排它们,但不会阻止协程代码的执行,直到它们最终完成。你仍然需要yield from
这些Task
或将它们传递给像asyncio.wait
这样的东西。 - Justin Turner Arthur