Python-tornado 中一段关于 gen 模块的使用, 其逻辑如何理解?

查看:154
本文介绍了Python-tornado 中一段关于 gen 模块的使用, 其逻辑如何理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

问题

如同自己当初理解回调一样, ( 一旦回调层次多了, 就感觉理解起来有点难度 )

详细问题已经在代码中注明, 见相关代码

相关代码

from tornado import gen
from tornado.ioloop import IOLoop
from tornado.queues import Queue

q = Queue(maxsize=2)

@gen.coroutine
def consumer():
    while True:
        item = yield q.get()
        try:
            print('Doing work on %s' % item)
            yield gen.sleep(0.01)
        finally:
            q.task_done()

@gen.coroutine
def producer():
    for item in range(5):
        yield q.put(item)
        print('Put %s' % item)

@gen.coroutine
def main():
    # Start consumer without waiting (since it never finishes).
    IOLoop.current().spawn_callback(consumer)
    yield producer()     # Wait for producer to put all tasks.
    yield q.join()       # Wait for consumer to finish all tasks.
    print('Done')

IOLoop.current().run_sync(main)

如上代码, 初看, 能懂它的大概意思, 但是具体一行一行看下来, 它的执行顺序就不是很清楚了, 下面是我的一些理解
1. 进入 main
2. consumer 派生一个回调, 在那里等待
3. producer 协程, 不断进入又出来( 我所理解的协程: 不断进入, 不断出来 )
4. q.join 协程, 卡住

以上理解, 有何错误的地方?

解决方案

yield 是让出时间片的意思。yield producer() 就是把时间交给 producer(),所以它自己是处于等待状态。

这里并没有(显式的)回调。

协程即「协作式多线程」,一个线程主动让出时间片给另外的线程。yield 一次,当然只让出一次。

main 这个协程会先在 yield producer() 处等待。五个任务生产完毕之后,它才会接着到 yield q.join() 这里等待任务处理完毕。

这篇关于Python-tornado 中一段关于 gen 模块的使用, 其逻辑如何理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆