协程的收益率与任务的收益率 [英] Yield from coroutine vs yield from task

查看:156
本文介绍了协程的收益率与任务的收益率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Guido van Rossum在2014年对Tulip / Asyncio的演讲中显示幻灯片

Guido van Rossum, in his speech in 2014 on Tulip/Asyncio shows the slide:


任务与协同


  • 比较:

  • Compare:


  • res = yield from some_coroutine(...)

  • res = yield from任务(some_coroutine(...))

任务可以不必等待就可以取得进展

Task can make progress without waiting for it


  • 作为您等待的其他日志

    • ie

    我完全错过了这一点。

    从我的观点来看,两个结构是相同的:

    I case因为调度程序与任务一起运行,则协同程序调用程序coroutine被暂停,直到被调用程序完成,然后可以自由地继续执行。

    From my point of view both constructs are identical:
    I case of bare coroutine - it gets scheduled, so the task is created anyways, because scheduler operates with Tasks, then coroutine caller coroutine is suspended until callee is done and then becomes free to continue execution.

    如果任务 - 所有相同 - 新任务被调度,并且调用程序coroutine等待其完成。

    In case of Task - all the same - new task is schduled and caller coroutine waits for its completion.

    在这两种情况下代码执行的方式有什么区别,以及开发者在实践中应该考虑的影响?

    What is the difference in the way that code executed in both cases and what impact it has that developer should consider in practice?

    ps

    链接

    p.s.
    Links to authoritative sources (GvR, PEPs, docs, core devs notes) will be very appreciated.

    推荐答案

    对于主叫方协议,程序从coroutine()产生的感觉就像一个函数调用(即,当coroutine()结束时它将再次获得控制)。

    For the calling side co-routine yield from coroutine() feels like a function call (i.e. it will again gain control when coroutine() finishes).

    从任务(coroutine())产生另一方面感觉更像是创建一个新的线程。 Task()几乎立即返回,很可能在 coroutine()完成之前,调用者获得控制权。

    yield from Task(coroutine()) on the other hand feels more like creating a new thread. Task() returns almost instantly and very likely the caller gains control back before the coroutine() finishes.

    f() th = threading.Thread(target = f,args = ()); th.start(); th.join()很明显,对吧?

    这篇关于协程的收益率与任务的收益率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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