关于python:Python中的并发编程asyncio库入门

26次阅读

共计 2343 个字符,预计需要花费 6 分钟才能阅读完成。

Python 中的并发编程容许你同时执行多个工作,进步程序的运行效率。在本文中,咱们将介绍 Python 中的 asyncio 库,它是一个基于异步 I / O 的并发编程库,用于编写高性能的网络和并发代码。

1. 为什么要应用 asyncio?

在传统的同步编程模型中,程序执行一个工作,直到它实现,而后能力执行下一个工作。而在异步编程模型中,当一个工作在期待 I / O 操作时(例如读取文件或网络申请),程序能够切换到其余工作执行。这样能够进步程序的执行效率,因为 CPU 不再被阻塞在期待 I / O 操作上。

asyncio 提供了一个基于事件循环的异步编程模型,容许你应用 asyncawait关键字编写异步代码。asyncio 还提供了许多高级性能,如并发、工作、协程、异步 I / O 操作等。

2. 应用 asyncio 创立一个简略的异步程序

以下是一个简略的异步程序示例,它应用 asyncio 库创立了一个异步工作:

import asyncio

async def hello_world():
    print("Hello World!")
    await asyncio.sleep(1)
    print("Hello again!")

async def main():
    task = asyncio.ensure_future(hello_world())
    await task

asyncio.run(main())

在这个示例中,咱们定义了一个 hello_world 协程,并在 main 协程中调用它。咱们应用 asyncio.run() 函数启动事件循环,执行 main 协程。

3. 应用 asyncio.gather()运行多个协程

当你须要同时运行多个协程时,能够应用 asyncio.gather() 函数。这个函数会期待所有协程实现,而后返回一个蕴含所有协程返回值的列表。

以下是一个示例,展现如何应用 asyncio.gather() 同时运行多个协程:

import asyncio

async def task1():
    print("Task 1 started")
    await asyncio.sleep(2)
    print("Task 1 finished")
    return "Task 1 result"

async def task2():
    print("Task 2 started")
    await asyncio.sleep(1)
    print("Task 2 finished")
    return "Task 2 result"

async def main():
    results = await asyncio.gather(task1(), task2())
    print(results)

asyncio.run(main())

在这个示例中,咱们定义了两个协程 task1task2,并在 main 协程中应用 asyncio.gather() 函数同时运行它们。输入结果显示 task1task2是并发执行的。

4. 小结

Python 的 asyncio 库提供了一个弱小的异步编程模型,帮忙你编写高性能的网络和并发代码。本文简要介绍了如何应用 asyncio 创立简略的异步程序,以及如何应用 asyncio.gather() 同时运行多个协程。通过把握 asyncio 的基本概念和应用办法,你能够为你的 Python 我的项目带来显著的性能晋升。

5. asyncio 中的其余性能

此外,asyncio 还提供了一些其余性能,例如创立 TCP 和 UDP 服务器、调度协程和工作等。以下是一些你可能会在理论我的项目中应用到的 asyncio 性能:

5.1 创立 TCP 服务器

以下是一个应用 asyncio 创立简略 TCP 服务器的示例:

import asyncio

async def handle_client(reader, writer):
    data = await reader.read(100)
    message = data.decode()
    print(f"Received: {message}")

    response = "Hello, client!"
    writer.write(response.encode())
    await writer.drain()

    writer.close()

async def main():
    server = await asyncio.start_server(handle_client, "127.0.0.1", 8080)

    async with server:
        await server.serve_forever()

asyncio.run(main())

5.2 调度协程和工作

你能够应用 asyncio.create_task()asyncio.ensure_future()函数创立工作,并应用 asyncio.wait()asyncio.gather()函数期待工作实现。

import asyncio

async def foo():
    print("Start foo")
    await asyncio.sleep(1)
    print("End foo")

async def bar():
    print("Start bar")
    await asyncio.sleep(2)
    print("End bar")

async def main():
    task1 = asyncio.create_task(foo())
    task2 = asyncio.create_task(bar())

    await asyncio.gather(task1, task2)

asyncio.run(main())

6. 总结

Python 的 asyncio 库为咱们提供了弱小的异步编程性能,使咱们可能编写更高效的并发程序。咱们曾经介绍了如何应用 asyncio 创立简略的异步程序、运行多个协程、创立 TCP 服务器以及调度协程和工作等。通过学习和实际这些性能,你将可能更好地利用 Python 的并发编程能力,进步你的程序性能。

正文完
 0