简体   繁体   English

如何在异步中使用线程?

[英]How to use thread in asyncio?

I want to new a thread to do a io task with consumer/producer pattern in a asyncio task:我想新建一个线程来在异步任务中使用消费者/生产者模式执行 io 任务:

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.但是由于消费者线程,异步任务无法执行。

Instead of explicitly managing the worker thread and a queue, you can use the thread pool built into asyncio (or create your own if you wish) and call run_in_executor to submit tasks to it.您可以使用内置在 asyncio 中的线程池(或根据需要创建自己的线程池)并调用run_in_executor向其提交任务,而不是显式管理工作线程和队列。 For example:例如:

import asyncio, time

def blocking_work(v):
    # this function is not async, it will be run in a separate thread
    time.sleep(v)
    print(f"log {v}")

async def work(v):
    # native asyncio work
    await asyncio.sleep(0.1)
    # followed by blocking IO wrapped in thread
    loop = asyncio.get_event_loop()
    await loop.run_in_executor(None, blocking_work, v)
    print(f"work {v}")

async def main():
    await asyncio.gather(*[work(i) for i in range(1, 5)])

asyncio.run(main())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM