python与future/promise(线程)的等价物是什么?

ewm0tg9j  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(502)

我来自C++世界,我在寻找STD::未来,STD::Python中的承诺。python中是否有一种等效的机制或其他方法来实现相同的功能?我知道asyncio.future,但我需要它来执行线程,而不是asyncio。
我使用的是第三方库(pjsua2),我直接从主线程调用它,但它在库创建的工作线程上下文中以异步回调的方式发送结果。
我期待着python对future/promise的支持,我希望我的应用程序代码是这样编写的:

future = wrap_foo(...)
if (future.get() != expected_result):
  throw Exception(...)

future1 = wrap_foo(...)
future2 = wrap_bar(...)

我计划用wrap_函数(其中库函数名为) Package 所有库异步调用,以创建future/promise对象。
我需要有多个期货等待的能力,所以我不能简单地使同步wrap_函数阻塞,直到结果准备好。

sshcrbum

sshcrbum1#

请参阅asyncio模块-

import asyncio

async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

asyncio.run(main())
hello
world

它支持协同程序-

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
started at 17:13:52
hello
world
finished at 17:13:55

和任务-

import asyncio

async def nested():
    return 42

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    print(await task)

asyncio.run(main())
42

和未来-

import asyncio

async def set_after(fut, delay, value):
    # Sleep for *delay* seconds.
    await asyncio.sleep(delay)

    # Set *value* as a result of *fut* Future.
    fut.set_result(value)

async def main():
    # Get the current event loop.
    loop = asyncio.get_running_loop()

    # Create a new Future object.
    fut = loop.create_future()

    # Run "set_after()" coroutine in a parallel Task.
    # We are using the low-level "loop.create_task()" API here because
    # we already have a reference to the event loop at hand.
    # Otherwise we could have just used "asyncio.create_task()".
    loop.create_task(
        set_after(fut, 1, '... world'))

    print('hello ...')

    # Wait until *fut* has a result (1 second) and print it.
    print(await fut)

asyncio.run(main())
hello ...
... world

相关问题