并发 - Python中的asyncio模块中的Future和Task的区别?
PHP中文网
PHP中文网 2017-04-18 10:07:01
0
1
566

问题一

按照官方文档的描述,Task是Futrue的一个subclass,标准库中也分别提供了create_task和create_future。请问这两者有功能上的什么区别?

问题二

对于ensure_future不是很理解,官方文档对于它的描述是:

asyncio.ensure_future(coro_or_future, *, loop=None)
Schedule the execution of a coroutine object: wrap it in a future. Return a Task object.If the argument is a Future, it is returned directly.

这段描述中wrap it in a future和Return a Task应该怎么理解,以下面这段代码为例子,factorial(name, number)显然是一个coroutine object,为什么wrap它到一个future对象后又返回一个Task,拜托大神解释下?

import asyncio

@asyncio.coroutine
def factorial(name, number):
    f = 1
    for i in range(2, number+1):
        print("Task %s: Compute factorial(%s)..." % (name, i))
        yield from asyncio.sleep(1)
        f *= i
    print("Task %s: factorial(%s) = %s" % (name, number, f))

loop = asyncio.get_event_loop()
tasks = [
    asyncio.ensure_future(factorial("A", 2)),
    asyncio.ensure_future(factorial("B", 3)),
    asyncio.ensure_future(factorial("C", 4))]
loop.run_until_complete(asyncio.gather(*tasks))
loop.close()

ps: 上面这段代码,如果tasks设置为下面这样,执行效果也是一样的,为什么官方文档的这个例子非要添加一个ensure_futrue,这有什么用途吗?

tasks = [
    factorial("A", 2),
    factorial("B", 3),
    factorial("C", 4)]
PHP中文网
PHP中文网

认证0级讲师

reply all(1)
大家讲道理

Second question

Simply put, you can regard the print of factorial as a return. Then, the following code is equivalent to waiting for the return of factorial. The above code is waiting for the return of asyncio.gather. And asyncio.gather will wait for the call of asyncio.ensure_future The result of the task.asyncio.ensure_future is returned immediately.

Of course it doesn’t work in this example, but for example, when you are already doing factorial("A", 2), what if you want to call factorial("B", 3), wait for factorial("A ", 2)? That is actually equivalent to a synchronous call. So asyncio.ensure_future can return immediately, and you can run factorial("A", 2) without waiting for the result of factorial("A", 2)

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!