← 返回首页

异步编程入门

📂 python ⏱ 2 min 266 words

异步编程入门

异步编程是Python处理高并发I/O操作的现代解决方案。通过 asyncio 模块,你可以编写单线程的并发代码,性能远超传统多线程。

基础概念

异步编程的核心概念:

import asyncio

async def hello():
    print("开始")
    await asyncio.sleep(1)  # 非阻塞等待
    print("结束")

# 运行协程
asyncio.run(hello())

定义协程

import asyncio

async def greet(name, delay):
    print(f"你好 {name}")
    await asyncio.sleep(delay)
    print(f"{name} 说完了")

# 顺序执行
async def main():
    await greet("Alice", 2)
    await greet("Bob", 1)

asyncio.run(main())  # 总耗时3秒

# 并发执行
async def main_concurrent():
    await asyncio.gather(
        greet("Alice", 2),
        greet("Bob", 1)
    )

asyncio.run(main_concurrent())  # 总耗时2秒

asyncio.gather

gather 用于并发运行多个协程:

import asyncio
import time

async def fetch_data(url, delay):
    print(f"开始获取 {url}")
    await asyncio.sleep(delay)
    print(f"完成 {url}")
    return f"数据 from {url}"

async def main():
    urls = ["url1", "url2", "url3"]
    start = time.time()

    # 并发执行
    results = await asyncio.gather(*[
        fetch_data(url, 1) for url in urls
    ])

    print(f"耗时: {time.time() - start:.2f}秒")
    print(results)

asyncio.run(main())  # 约1秒

asyncio.wait

更灵活的并发控制:

import asyncio

async def task(name, duration):
    await asyncio.sleep(duration)
    return f"{name} 完成"

async def main():
    tasks = [
        task("快", 1),
        task("中", 2),
        task("慢", 3)
    ]

    # 等待第一个完成
    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    for t in done:
        print(t.result())

asyncio.run(main())  # 约1秒

异步上下文管理器

import asyncio

class AsyncResource:
    async def __aenter__(self):
        print("获取资源")
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        print("释放资源")
        return False

    async def use(self):
        await asyncio.sleep(1)
        return "使用资源"

async def main():
    async with AsyncResource() as resource:
        result = await resource.use()
        print(result)

asyncio.run(main())

异步迭代器

import asyncio

class AsyncCounter:
    def __init__(self, stop):
        self.current = 0
        self.stop = stop

    def __aiter__(self):
        return self

    async def __anext__(self):
        if self.current >= self.stop:
            raise StopAsyncIteration
        await asyncio.sleep(0.1)
        self.current += 1
        return self.current

async def main():
    async for num in AsyncCounter(5):
        print(num)

asyncio.run(main())

常见错误

import asyncio

# 错误:在同步代码中调用协程
def wrong():
    await asyncio.sleep(1)  # SyntaxError

# 错误:创建任务但不await
async def also_wrong():
    asyncio.create_task(some_coroutine())  # 可能被垃圾回收

# 正确做法
async def correct():
    task = asyncio.create_task(some_coroutine())
    await task

异步编程是现代Python开发的必备技能,特别适合处理网络I/O密集型应用。