Python 3:Asyncio和Future

时间:2018-04-10 18:49:58

标签: python-3.x

https://tutorialedge.net/python/concurrency/getting-started-with-asyncio-python/的以下代码中,它使用asyncio.ensure_future来包装任务。

但是,它从未在myCoroutine()内设置未来对象。为什么代码仍然有效?

import asyncio
import random

async def myCoroutine(id):
    process_time = random.randint(1,5)
    await asyncio.sleep(process_time)
    print("Coroutine: {}, has successfully completed after {} seconds".format(id, process_time))

async def main():
    tasks = []
    for i in range(10):
        tasks.append(asyncio.ensure_future(myCoroutine(i)))

    await asyncio.gather(*tasks)


loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(main())
finally:
    loop.close()

1 个答案:

答案 0 :(得分:1)

您无需明确创建.faq .collapsed { /*display: none;*/ position: absolute !important; top: -9999px !important; left: -9999px !important; } 对象。 Future已经使得async def myCoroutine调用返回的行为类似于Future对象,因此您可以使用myCoroutine()