asyncio的常用方法

以下是一些 asyncio 常用方法的代码示例,以及相应的中文说明:

  1. asyncio.run() - 运行顶层的异步函数。

    async def main():
        print("Hello, asyncio!")
    
    asyncio.run(main())
    

    中文说明:asyncio.run() 启动事件循环,运行 main() 这个顶层异步函数。

  2. asyncio.create_task() - 创建并返回一个任务。

    async def my_task(name):
        print(f"Task {name} is running")
    
    async def main():
        task1 = asyncio.create_task(my_task("A"))
        task2 = asyncio.create_task(my_task("B"))
    
        await task1
        await task2
    
    asyncio.run(main())
    

    中文说明:在 main() 函数中,我们创建了两个异步任务 task1task2,分别运行 my_task() 函数。

  3. asyncio.gather() - 等待多个异步操作完成。

    async def my_task(name):
        await asyncio.sleep(1)
        return f"Result of task {name}"
    
    async def main():
        results = await asyncio.gather(
            my_task("A"), my_task("B"), return_exceptions=True
        )
        print(results)
    
    asyncio.run(main())
    

    中文说明:asyncio.gather() 用于等待多个异步任务完成,并返回它们的返回值或异常。

  4. asyncio.sleep() - 异步等待一段时间。

    async def main():
        print("Start sleeping for 2 seconds")
        await asyncio.sleep(2)
        print("Woke up after 2 seconds")
    
    asyncio.run(main())
    

    中文说明:asyncio.sleep() 允许当前任务在指定的秒数内暂停执行,同时事件循环可以运行其他任务。

  5. asyncio.get_event_loop() - 获取当前线程的事件循环。

    loop = asyncio.get_event_loop()
    print("Current event loop:", loop)
    

    中文说明:获取当前线程的事件循环实例。

  6. asyncio.open_connection() - 异步打开 TCP 连接。

    async def fetch(host, port):
        reader, writer = await asyncio.open_connection(
            host, port, loop=asyncio.get_event_loop()
        )
        print(f"Connected to {host}:{port}")
    
    asyncio.run(fetch('example.com', 80))
    

    中文说明:asyncio.open_connection() 用于异步地打开到指定主机和端口的 TCP 连接。

  7. asyncio.streams.open_connection() - 打开流式连接。

    async def main():
        reader, writer = await asyncio.streams.open_connection('example.com', 80)
        print("Connection opened")
    
    asyncio.run(main())
    

    中文说明:asyncio.streams.open_connection() 用于打开一个流式的连接,返回一个读取器和一个写入器。

  8. asyncio.Lock - 获取一个异步锁。

    lock = asyncio.Lock()
    
    async def critical_section():
        async with lock:
            # 临界区代码
            print("Critical section is running")
    
    async def main():
        await asyncio.gather(critical_section(), critical_section())
    
    asyncio.run(main())
    

    中文说明:使用 asyncio.Lock() 创建一个异步锁,以保护临界区代码,防止多个任务同时执行。

  9. asyncio.Queue - 使用异步队列。

    queue = asyncio.Queue()
    
    async def producer():
        for i in range(5):
            await queue.put(i)
            print(f"Produced {i}")
    
    async def consumer():
        while True:
            item = await queue.get()
            print(f"Consumed {item}")
            queue.task_done()
    
    async def main():
        await asyncio.gather(producer(), consumer())
    
    asyncio.run(main())
    

    中文说明:创建一个异步队列 queueproducer() 函数生产数据并放入队列,consumer() 函数从队列中取出并消费数据。

posted @ 2024-06-24 10:46  linux星  阅读(4)  评论(0编辑  收藏  举报