I want to new a thread to do a io task with consumer/producer pattern in a asyncio task:
import asyncio
import threading
import time
import queue
q = queue.Queue()
def consumer():
while True:
v = q.get()
time.sleep(v)
print(f"log {v}")
async def work(v):
await asyncio.sleep(0.1)
print(f"work {v}")
async def main():
t = threading.Thread(target=consumer, daemon=True)
t.start()
for i in range(1, 5):
print(f"start {i}")
q.put(i)
loop.create_task(work(i))
print(f"done {i}")
t.join()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.run_forever()
But the asyncio task cannot be execute because of consumer thread.
how to use thread for doing IO in asyncio?isdon't do this. The questionhow to use threads for blocking operations in asynciois legit.asyncio.loop.run_in_executor, combined withProcessPoolExecutor