我的代码如下。我希望这两个睡眠可以共享相同的时间框架,并花费1+2*3=7秒来运行脚本。但是似乎发生了一些错误,所以仍然需要3*(1+2)秒。
你知道如何修改代码吗?
import asyncio
async def g():
for i in range(3):
await asyncio.sleep(1)
yield i
async def main():
async for x in g():
print(x)
await asyncio.sleep(2)
loop = asyncio.get_event_loop()
res = loop.run_until_complete(main())
loop.close()发布于 2019-07-05 16:53:58
作为对队列执行此操作的替代方法,此解决方案将期货链连接在一起,以便未来的结果是当前项和检索下一项的另一个未来(可以说,类似于链接列表):
from asyncio import sleep, get_event_loop, run, create_task
async def aiter(fut, async_generator):
try:
async for item in async_generator:
fut, prev_fut = get_event_loop().create_future(), fut
prev_fut.set_result((item, fut))
else:
fut.set_exception(StopAsyncIteration())
except Exception as e:
fut.set_exception(e)
async def concurrent(async_generator):
fut = get_event_loop().create_future()
create_task(aiter(fut, async_generator))
try:
while True:
item, fut = await fut
yield item
except StopAsyncIteration as e:
return额外的好处是,该解决方案将正确地处理g()中发生的异常,方法是将main()方法中的异常重命名为具有对调试有用的追溯功能。
https://stackoverflow.com/questions/56902202
复制相似问题