如何从阻塞函数中获取结果?

How do I get results from the blocking function?

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())

而 ab() 函数的 print(111)

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...

但我想在 return 结果

时打印 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是一个阻塞函数,不能修改。我想不出解决办法。我需要帮助。

如果您从某个地方等待 run_in_executor 的结果,您将收到它执行的阻塞函数的 return 值。由于您已经在后台使用 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

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