【问题标题】:How do I get results from the blocking function?如何从阻塞函数中获取结果?
【发布时间】:2020-09-25 16:33:07
【问题描述】:
import asyncio
import time

def abab():
    for i in range(10):
        print(i)
        time.sleep(1)
    return 10000

async def ab():
    while True:
        print(111)
        time.sleep(1)
        await asyncio.sleep(0.01)


async def main():
    abc = asyncio.create_task(ab())
    loop = asyncio.get_event_loop()
    a = loop.run_in_executor(None, abab)
    await abc

asyncio.run(main())

while print(111) of ab() 函数

10秒后,我想得到abab结果10000。

abab 函数必须是阻塞函数。不是异步函数

这个例子是这样打印的

0 111 1 111 2 111 3 111 4 111 5 111 6 111 7 111 8 111 9 111 111 111 111...

但我想在返回结果时打印 10000

0 111 1 111 2 111 3 111 4 111 5 111 6 111 7 111 8 111 9 111 10000 111 111 111...

这其实是一个例子,但是在实际代码中,abab是一个阻塞函数,不能修改。我想不出解决办法。我需要帮助。

【问题讨论】:

    标签: python-asyncio python-3.7


    【解决方案1】:

    如果您从某个地方等待run_in_executor 的结果,您将收到它执行的阻塞函数的返回值。由于您已经使用create_task 在后台运行ab(),因此您只需等待调用run_in_executor 以获取abab() 的结果:

    async def main():
        # spawn ab() in the background
        abc = asyncio.create_task(ab())
        loop = asyncio.get_event_loop()
        # wait for abab() to finish, allowing ab() to run
        abab_result = await loop.run_in_executor(None, abab)
        # print (or otherwise process) the result of abab
        print(abab_result)
        # continue waiting for ab()
        await abc
    

    通过此更改,程序的输出与您请求的输出相匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多