返回

协程入门:从生成器到协程,携手踏上异步编程之旅

闲谈

对于 Python 初学者而言,协程似乎是一个遥不可及的概念,令人望而生畏。然而,通过分步学习并掌握核心概念,我们就能揭开协程的神秘面纱,轻松驾驭异步编程和并发编程的技巧。

第一章:生成器——协程的垫脚石

生成器是协程的基础,也是理解协程的关键。生成器函数使用 yield 将函数暂停并返回一个生成器对象。我们可以在生成器对象上调用 next() 方法来逐步获取生成的值。

def generator_function():
    yield 1
    yield 2
    yield 3

generator = generator_function()
print(next(generator))  # 输出:1
print(next(generator))  # 输出:2
print(next(generator))  # 输出:3

第二章:协程函数——协程的灵魂

协程函数是 Python 2.5 中引入的特性,它本质上是一种可以暂停并恢复执行的函数。协程函数使用 async 关键字定义,并使用 await 关键字来挂起协程函数的执行,等待其他协程函数完成。

async def coroutine_function():
    await asyncio.sleep(1)
    return "Hello, world!"

asyncio.run(coroutine_function())  # 输出:Hello, world!

第三章:任务切换——协程的幕后英雄

协程之所以能够并发执行,得益于任务切换机制。任务切换是指操作系统在不同任务之间切换执行的机制。当一个协程函数被挂起时,操作系统会将执行权交给其他协程函数,直到挂起的协程函数恢复执行。

async def coroutine_function1():
    await asyncio.sleep(1)
    return "Hello, world!"

async def coroutine_function2():
    await asyncio.sleep(2)
    return "Goodbye, world!"

async def main():
    task1 = asyncio.create_task(coroutine_function1())
    task2 = asyncio.create_task(coroutine_function2())
    await task1
    await task2

asyncio.run(main())  # 输出:Hello, world! Goodbye, world!

结语

协程是理解 Python 中异步编程和并发编程的关键。通过从生成器到协程函数的逐步学习,我们掌握了协程的核心概念。如今,协程已经广泛应用于网络编程、数据处理和人工智能等领域。希望这篇文章能够帮助您揭开协程的神秘面纱,开启异步编程之旅。