I have the following scenario:
- I have a blocking, synchronous generator
- I have an non-blocking, async function
I would like to run blocking generator (executed in a ThreadPool
) and the async
function on the event loop. How do I achieve this?
The following function simply prints the output from the generator, not from sleep
function.
Thanks!
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())
if __name__ == '__main__':
main()