相关疑难解决方法(0)

asyncio 中的同步发电机

我有以下场景:

  1. 我有一个阻塞同步发电机
  2. 我有一个非阻塞异步函数

我想运行阻塞生成器(在 a 中执行ThreadPool)和async事件循环上的函数。我该如何实现这一目标?

以下函数仅打印生成器的输出,而不是sleep函数的输出。

谢谢!

from concurrent.futures import ThreadPoolExecutor

import numpy as np
import asyncio
import time


def f():
    while True:
        r = np.random.randint(0, 3)
        time.sleep(r)
        yield r


async def gen():
    loop = asyncio.get_event_loop()
    executor = ThreadPoolExecutor()
    gen = await loop.run_in_executor(executor, f)
    for item in gen:
        print(item)
        print('Inside generator')


async def sleep():
    while True:
        await asyncio.sleep(1)
        print('Inside async sleep')


async def combine():
    await asyncio.gather(sleep(), gen())


def main():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(combine()) …
Run Code Online (Sandbox Code Playgroud)

async-await python-asyncio concurrent.futures

3
推荐指数
1
解决办法
2162
查看次数