Board logo

标题: Python并发之异步I/O(async,await)-2 [打印本页]

作者: look_w    时间: 2019-3-4 18:41     标题: Python并发之异步I/O(async,await)-2

asyncio的几个重要结构

我这里都用英文展示,原生,易理解。怎么翻译都绕口。

event loop:

    An event loop essentially manages and distributes the execution of different tasks. It registers them and handles distributing the flow of control between them.

Coroutines:

    Coroutines are special functions that work similarly Python generators that on await they release the flow of control back to the event loop. A coroutine needs to be scheduled to run using the event loop, to do this we create a Task, which is a type of Future.

Futures:

    Futures are objects that represent the result of a task that may or may not have been executed. This result may be an exception.

理解基本架构很重要,理解协程,future,task的概念重中之重,至于什么内部实现,真的挺复杂的,无需关心。

在这边的时候我卡了很长时间:future与Task的区别是什么????

future在多线程说过,future表示终将发生的事情,而确定某件事会发生的唯一方式是执行的时间已经排定。(你不排定它,它就是个协程),那怎么排定?

BaseEventLoop.create_task(...) 或者 asyncio.ensure_future方法接收一个协程,排定它的运行时间,然后返回一个asyncio.Task 实例——也是 asyncio.Future 类的实例,因为 Task 是Future 的子类,用于包装协程。这与调用 Executor.submit(...) 方法创建Future实例是一个道理

这句话我读了好多遍,意思是不是说future跟task是同一样东西。对于event loop来说,一个包装了协程的future,就是循环中的一个task?我是这么理解的。

我们无法确定future啥时完成结束,但是总归结束(无论报错还是返回值)的,因为我们已经给它排定了时间。




欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0