gpt4 book ai didi

python - 异步协程

转载 作者:太空宇宙 更新时间:2023-11-03 16:20:40 24 4
gpt4 key购买 nike

我以为我已经和 David Beazley 的协程搞清楚了,非常好 presentation但我无法将其与 PEP-492 中描述的新语法完全协调。 。

在演讲中,他解释了如何将协程视为一条管道,它被推送到而不是像生成器中那样被拉出。

例如:

# cofollow.py
#
# A simple example showing how to hook up a pipeline with
# coroutines. To run this, you will need a log file.
# Run the program logsim.py in the background to get a data
# source.

from coroutine import coroutine

# A data source. This is not a coroutine, but it sends
# data into one (target)

import time
def follow(thefile, target):
thefile.seek(0,2) # Go to the end of the file
while True:
line = thefile.readline()
if not line:
time.sleep(0.1) # Sleep briefly
continue
target.send(line)

# A sink. A coroutine that receives data

@coroutine
def printer():
while True:
line = (yield)
print line,

# Example use
if __name__ == '__main__':
f = open("access-log")
follow(f,printer())

如何使用这一新语法实现 printer() 协程?我还没有看到协程被推送到使用这种新语法的示例。可能吗?

最佳答案

你所拥有的并不是 asyncio 模块和/或 PEP-492 意义上的协程。正如 PEP 本身所说:

[This PEP] is relevant only to the kind of coroutine that uses yield as a signal to the scheduler, indicating that the coroutine will be waiting until an event (such as IO) is completed.

  1. 您的示例中不涉及调度程序(事件循环),并且
  2. 协程不使用 yield 仅“作为调度程序的信号”;它实际上是用它来读取数据。

关于python - 异步协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com