简体   繁体   English

如何编写自己的 python awaitable function 即不仅调用其他异步函数?

[英]How to write your own python awaitable function that is not only calls other async functions?

I have one blocking function:我有一个阻塞 function:

def blocking_function():
    doing.start_preparing()
    while not doing.is_ready():
        pass
    return doing.do()

I want to change it into an async function.我想将其更改为异步 function。

I've read some source code of asyncio, and I've found this two options:我已经阅读了一些 asyncio 的源代码,并且找到了这两个选项:

@types.coroutine
def yield_option() -> typing.Generator:
    doing.start_preparing()
    while not doing.is_ready():
        yield
    return doing.do()

def future_and_call_soon_option() -> asyncio.Future:
    doing.start_preparing()
    loop = asyncio.get_running_loop()
    future = loop.create_future()
    def inner():
        if not doing.is_ready():
            loop.call_soon(inner)
        else:
            future.set_result(doing.do())
    inner()
    return future
async def main():
    await asyncio.gather(yield_option(), future_and_call_soon_option()) #runs concurently

asyncio.run(main())

Both of these options do work but which of them is better?这两个选项都有效,但哪个更好? Or is there any third option that is better to use?还是有更好用的第三种选择?

How about:怎么样:

async def blocking_function():
    doing.start_preparing()
    while not doing.is_ready():
        await asyncio.sleep(0)
    return doing.do()

This will cooperate with other tasks.这将与其他任务合作。 It is simple and would probably be acceptable in practice if the blocking functions are fast enough.如果阻塞函数足够快,它很简单并且在实践中可能是可以接受的。 But if the blocking functions take a significant amount of time it would be better to move them to another thread.但是如果阻塞函数需要大量时间,最好将它们移动到另一个线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM