Skip to content

Instantly share code, notes, and snippets.

@wwj718
Created January 26, 2018 08:13
Show Gist options
  • Save wwj718/09ce82f62bc8b5f4dde4ce3d67111998 to your computer and use it in GitHub Desktop.
Save wwj718/09ce82f62bc8b5f4dde4ce3d67111998 to your computer and use it in GitHub Desktop.
import asyncio
# 一个对future进行赋值的函数
async def slow_operation(future):
await asyncio.sleep(1)
# 给future赋值
future.set_result('Future is done!')
loop = asyncio.get_event_loop()
# 创建一个future
future1 = asyncio.Future()
# 使用ensure_future 创建Task
asyncio.ensure_future(slow_operation(future1))
future2 = asyncio.Future()
asyncio.ensure_future(slow_operation(future2))
# gather Tasks,并通过run_uniti_complete来启动、终止loop
loop.run_until_complete(asyncio.gather(future1, future2))
print(future1.result())
print(future2.result())
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment