Learn Python · 14/15

Asynchronous Programming & Concurrency

3 min read

异步编程与并发

你好呀!欢迎来到 Python 中令人兴奋的异步编程和并发世界。🚀 这听起来可能很复杂,但别担心,我们会一步一步地分解它。准备好让你的程序运行得更快、更高效了吗?让我们开始吧!

📜 目录

  1. 并发与并行简介
  2. Asyncio 基础:async 和 await
  3. 并发运行异步任务
  4. 线程和多进程简介

1. 并发与并行简介

在我们深入研究代码之前,让我们先来了解一下两个经常被混淆的关键概念:并发和并行。

🤔 问题是什么?

想象一下,你正在编写一个程序,需要从三个不同的网站下载三个图片。如果你一个接一个地下载它们,你的程序会花费大量时间等待每个下载完成,然后才开始下一个。这非常低效,尤其是在你的程序无事可做只能等待的时候。

💡 解决方案:并发与并行

这就是并发和并行的用武之地。它们都是关于同时做多件事情以提高效率的。

  • 并发 (Concurrency):指的是程序的结构,它允许任务在重叠的时间段内取得进展。这并不意味着它们在同一时刻被执行。把它想象成一个杂耍演员,他同时处理多个球。在任何给定的瞬间,他只接触一个球,但他通过在它们之间快速切换来保持所有球都在空中。

  • 并行 (Parallelism):指的是同时执行多个任务。这需要多个处理器(CPU 核心)。把它想象成一个有多个厨师的厨房,他们都在同一时间准备一道菜的不同部分。

一个真实世界的场景:做早餐

想象一下你正在做早餐。你有三项任务:

  1. 烤面包
  2. 煎鸡蛋
  3. 煮咖啡
  • 非并发/非并行的方法:你会先把面包放进烤面包机,然后盯着它看,直到它烤好。然后,你会开始煎鸡蛋,再盯着它看,直到它煎好。最后,你会开始煮咖啡,再等着它煮好。这种方法非常慢,因为你在等待的时候什么都没做。

  • 并发的方法:你会先把面包放进烤面包机,然后在你等待它烤好的时候,开始煎鸡蛋。在鸡蛋煎好的时候,你开始煮咖啡。你一次只做一件事,但在任务之间切换,利用等待时间。

  • 并行的方法:如果你有两个朋友帮忙(多核),你可以让一个人烤面包,一个人煎鸡蛋,你来煮咖啡。所有三项任务都在同一时间发生。

在 Python 中...

  • 并发 通常用于 I/O 密集型任务(例如,网络请求、文件读写),这时你的程序花费大量时间等待外部资源。Python 的 asyncio 和 threading 就属于这一类。
  • 并行 通常用于 CPU 密集型任务(例如,复杂的数学计算、视频处理),这时你需要多个 CPU 核心来同时进行大量的计算。Python 的 multiprocessing 模块就是为这个目的而设计的。

🤓 有趣的事实:由于 Python 的全局解释器锁(GIL),一个 Python 进程中的多个线程不能在多核 CPU 上并行执行 Python 字节码。这就是为什么对于 CPU 密集型任务,我们使用多进程来绕过 GIL。


2. Asyncio 基础:async 和 await

现在我们来谈谈 Python 中实现并发的一种现代而强大的方式:asyncio。

🤔 问题是什么?

正如我们之前提到的,I/O 操作(比如向服务器发出请求、读取文件或查询数据库)可能会很慢。在传统的同步代码中,当你的程序等待这些操作完成时,它会完全阻塞,什么也不做。这就像在电话上等待时,你什么也做不了,只能听着烦人的等待音乐。

💡 解决方案:async 和 await

asyncio 允许你在等待一个慢速操作完成时,切换到另一个任务。它使用了一种叫做“事件循环”的东西来管理和分发任务。为了让 asyncio 发挥它的魔力,你需要使用两个新的关键字:async 和 await。

  • async def: 这个关键字用于定义一个协程。协程是一种可以暂停和恢复执行的特殊函数。你可以把它看作是一个知道如何在被要求时暂停的函数。

  • await: 这个关键字用在 async def 函数内部,用于调用另一个协程。它告诉事件循环:“嘿,我要等待这个操作完成。在我等待的时候,你可以去做些别的事情。”

让我们来看一个例子吧!

假设我们有一个函数,它假装从一个服务器获取数据,这需要一些时间。

python
import asyncio
import time

async def fetch_data(delay, name):
    print(f"开始获取 {name}...")
    await asyncio.sleep(delay) # 模拟一个 I/O 操作,比如网络请求
    print(f"完成获取 {name}!")
    return {"data": f"来自 {name} 的一些数据"}

async def main():
    start_time = time.time()
    
    print("开始执行程序...")
    task1 = await fetch_data(2, "任务1")
    task2 = await fetch_data(1, "任务2")
    
    print(f"任务1的结果: {task1}")
    print(f"任务2的结果: {task2}")
    
    end_time = time.time()
    print(f"程序总共耗时: {end_time - start_time:.2f} 秒")

# 在 Python 3.7+ 中,你可以这样运行一个 async 函数
asyncio.run(main())

如果你运行上面的代码,你会看到以下输出:

prolog
开始执行程序...
开始获取 任务1...
完成获取 任务1!
开始获取 任务2...
完成获取 任务2!
任务1的结果: {'data': '来自 任务1 的一些数据'}
任务2的结果: {'data': '来自 任务2 的一些数据'}
程序总共耗时: 3.00 秒

正如你所看到的,这个程序耗时 3 秒,因为它一个接一个地等待每个任务完成。这并没有真正利用 asyncio 的优势。在下一节中,我们将学习如何让它们真正地并发运行。


3. 并发运行异步任务

我们已经学习了如何创建协程,但我们如何让它们同时运行以节省时间呢?

🤔 问题是什么?

在我们之前的例子中,尽管我们使用了 async 和 await,但任务仍然是按顺序执行的。await fetch_data(2, "任务1") 会阻塞 main 函数,直到它完成,然后才会开始 fetch_data(1, "任务2")。我们并没有真正地并发。

💡 解决方案:asyncio.gather()

asyncio 提供了一个非常有用的函数叫做 asyncio.gather()。这个函数接收一个或多个协程,并将它们安排为并发运行。它会等待所有协程完成,然后以相应的顺序返回它们的结果。

让我们修改一下之前的例子:

python
import asyncio
import time

async def fetch_data(delay, name):
    print(f"开始获取 {name}...")
    await asyncio.sleep(delay) # 模拟一个 I/O 操作
    print(f"完成获取 {name}!")
    return {"data": f"来自 {name} 的一些数据"}

async def main():
    start_time = time.time()
    
    print("开始执行程序...")
    
    # 使用 asyncio.gather() 并发运行任务
    results = await asyncio.gather(
        fetch_data(2, "任务1"),
        fetch_data(1, "任务2")
    )
    
    print(f"所有任务的结果: {results}")
    
    end_time = time.time()
    print(f"程序总共耗时: {end_time - start_time:.2f} 秒")

asyncio.run(main())

现在,输出看起来会是这样的:

prolog
开始执行程序...
开始获取 任务1...
开始获取 任务2...
完成获取 任务2!
完成获取 任务1!
所有任务的结果: [{'data': '来自 任务1 的一些数据'}, {'data': '来自 任务2 的一些数据'}]
程序总共耗时: 2.00 秒

发生了什么? 😮

  • 我们用 asyncio.gather() 把我们的 fetch_data 调用包裹起来。
  • gather 立即安排了两个任务在事件循环中运行。
  • 程序打印出“开始获取 任务1...”和“开始获取 任务2...”。
  • 当 任务1 await asyncio.sleep(2) 时,它会暂停并把控制权交还给事件循环。事件循环看到 任务2 已经准备好运行了,于是就开始运行它。
  • 任务2 在 1 秒后完成,然后 任务1 在 2 秒后完成。
  • 总的运行时间大约是 2 秒,这是最长的那个任务所花费的时间,而不是所有任务时间的总和!我们节省了一整秒!

这就是 asyncio 的力量!对于有大量 I/O 操作的应用程序(比如 web 服务器、API 客户端或爬虫),这可以带来巨大的性能提升。


4. 线程和多进程简介

虽然 asyncio 非常棒,但它并不是 Python 中实现并发的唯一方式。让我们来简单了解一下另外两个经典的方法:线程和多进程。

🤔 问题是什么?

  • I/O 密集型任务:就像我们之前讨论过的,你的程序花费大量时间等待网络或磁盘。
  • CPU 密集型任务:你的程序需要进行大量的计算(比如处理一个大图片或运行一个复杂的算法),这会让你的 CPU 满负荷运转。

asyncio 非常适合 I/O 密集型任务,但对于 CPU 密集型任务,它就无能为力了,因为它是在一个线程中运行的。

💡 解决方案:threading 和 multiprocessing

  • 线程 (threading) 🧵

    线程就像在一个进程中运行的迷你进程。它们共享相同的内存空间,这使得它们之间共享数据变得容易(但也很危险,如果你不小心的话!)。

    • 适用场景:和 asyncio 一样,线程非常适合 I/O 密集型任务。当一个线程在等待 I/O 时,操作系统可以切换到另一个线程来执行工作。
    • 优点:创建线程比创建进程开销更小。
    • 缺点:由于 Python 的全局解释器锁(GIL),线程不能实现真正的 CPU 密集型任务并行。

    一个简单的线程示例:

    python
    import threading
    import time
    
    def long_task(name):
        print(f"任务 {name} 开始")
        time.sleep(2)
        print(f"任务 {name} 完成")
    
    thread1 = threading.Thread(target=long_task, args=("A",))
    thread2 = threading.Thread(target=long_task, args=("B",))
    
    thread1.start()
    thread2.start()
    
    thread1.join() # 等待 thread1 完成
    thread2.join() # 等待 thread2 完成
    
    print("所有线程都已完成")
  • 多进程 (multiprocessing) 🏭

    多进程意味着你的程序会创建多个独立的 Python 解释器进程。每个进程都有自己的内存空间和自己的 GIL。

    • 适用场景:多进程是 CPU 密集型任务的理想选择。由于每个进程都有自己的 GIL,你可以利用多核 CPU 来实现真正的并行。
    • 优点:可以绕过 GIL,实现真正的并行计算。
    • 缺点:创建进程的开销比创建线程要大。进程间通信(IPC)比线程间共享内存更复杂。

    一个简单的多进程示例:

    python
    import multiprocessing
    import time
    
    def cpu_bound_task(name):
        print(f"进程 {name} 开始")
        # 模拟一个 CPU 密集型任务
        count = 0
        for i in range(10**7):
            count += i
        print(f"进程 {name} 完成")
    
    if __name__ == "__main__":
        process1 = multiprocessing.Process(target=cpu_bound_task, args=("A",))
        process2 = multiprocessing.Process(target=cpu_bound_task, args=("B",))
    
        process1.start()
        process2.start()
    
        process1.join()
        process2.join()
    
        print("所有进程都已完成")

    重要提示:在多进程中,if __name__ == "__main__": 这行代码很重要,它可以防止在 Windows 等操作系统上出现无限创建子进程的问题。

总结

  • 并发 是关于结构,并行 是关于执行。
  • 使用 asyncio 来处理有大量 I/O 操作的现代网络应用。
  • 使用 threading 来处理 I/O 密集型任务,或者在你需要与不支持 asyncio 的旧代码库集成时。
  • 使用 multiprocessing 来处理需要大量计算能力的 CPU 密集型任务,并充分利用你的多核 CPU。

📚 进一步阅读和参考资料

Challenge

Challenge: Concurrent Data Fetching with asyncio

Your task is to write a Python script that uses the asyncio library to simulate fetching data from three different API endpoints concurrently. This will demonstrate how asyncio can handle I/O-bound operations efficiently without waiting for each one to complete sequentially.

Requirements:

  1. Create a coroutine fetch_data:

    • It must be an async function.
    • It should accept two arguments: endpoint_name (a string) and delay (a float representing the time to fetch).
    • Inside the function, it should first print Fetching data from {endpoint_name}....
    • Then, it must simulate the network I/O operation by using await asyncio.sleep(delay).
    • After the wait, it should print Data received from {endpoint_name}.
    • Finally, it should return a dictionary with the fetched data, for example: {'endpoint': endpoint_name, 'status': 'success'}.
  2. Create a main coroutine:

    • It must be an async function.
    • Inside main, record the starting time using time.time().
    • Create three concurrent tasks by calling fetch_data with the following arguments:
      1. endpoint_name='users', delay=1.0
      2. endpoint_name='products', delay=2.0
      3. endpoint_name='orders', delay=0.5
    • Use asyncio.gather() to run these three tasks concurrently and collect their results.
    • After gather completes, record the ending time.
    • Print the list of results returned by asyncio.gather().
    • Calculate and print the total execution time.
  3. Run the script:

    • Use the standard if __name__ == "__main__": block to run your main coroutine using asyncio.run().

Expected result

The exact order of the "Fetching..." print statements may vary slightly due to the nature of concurrent execution, but they should all appear at the beginning of the program's execution.

The final output should look similar to this:

text
Fetching data from users...
Fetching data from products...
Fetching data from orders...
Data received from orders
Data received from users
Data received from products
Results: [{'endpoint': 'users', 'status': 'success'}, {'endpoint': 'products', 'status': 'success'}, {'endpoint': 'orders', 'status': 'success'}]
Total execution time: 2.00... seconds

Key Verification Points:

  • The list of results contains three dictionaries, one for each endpoint.
  • Most importantly, the total execution time must be approximately 2 seconds (the duration of the longest task), not the sum of all delays (3.5 seconds). This demonstrates that the tasks ran concurrently, not sequentially.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.