捕获并发执行的三io函数的返回值
项目描述
trio-future
概述
trio-future
允许您捕获并发执行的三io函数的返回值。它是一种与使用三io通道进行通信相比,更像使用常规函数进行编程的替代方案。
考虑以下简单的回声函数示例
async def echo(a: str) -> str:
await trio.sleep(0.5)
return a
我们可以调用我们的函数,并在我们准备好时返回其结果
async with trio.open_nursery() as nursery:
# Call trio_future.run to synchronously get back a Future
future = trio_future.run(nursery, echo, "hello")
# When we call `await` and yield to scheduler, our function begins executing
await trio.sleep(0.1)
# We can `await` the function when we are ready
hello = await future.get()
# hello == "hello"
一个常见的用例是并发运行多个任务,并等待它们全部完成。 trio-future
有一个类似于 asyncio.gather
的 gather
函数来完成此操作
async with trio.open_nursery() as nursery:
fut_1 = run(nursery, echo, "hello")
fut_2 = run(nursery, echo, "world")
# Call `gather` to package the two Futures into a single Future object.
# Note that this is again a synchronous function.
joined_future = gather(nursery, [fut_1, fut_2])
# Again, when we `await` the result, we yield to the scheduler. This time, both
# of our futures will execute concurrently.
hello_world = await join_future.get()
# hello_world = ["hello", "world"]
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定要选择哪个,请了解更多关于 安装包 的信息。
源分发
trio-future-0.1.1.tar.gz (4.2 kB 查看散列)
构建分发
trio_future-0.1.1-py3-none-any.whl (4.4 kB 查看散列)