<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>异步 on 老张开工了</title>
    <link>/%E5%BC%82%E6%AD%A5/</link>
    <description>Recent content in 异步 on 老张开工了</description>
    <generator>Hugo</generator>
    <language>zh-cn</language>
    <lastBuildDate>Tue, 26 May 2026 00:00:00 +0000</lastBuildDate>
    <atom:link href="/%E5%BC%82%E6%AD%A5/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>异步编程与 asyncio</title>
      <link>/posts/2026/05/asyncio/</link>
      <pubDate>Tue, 26 May 2026 00:00:00 +0000</pubDate>
      <guid>/posts/2026/05/asyncio/</guid>
      <description>异步编程概述 asyncio 是 Python 用于编写并发代码的标准库，使用 async/await 语法。它是处理 I/O 密集型高并发任务的最佳方案——比如 Web 服务器、爬虫、API 调用等。&#xA;与多线程不同，asyncio 在单线程内实现并发，没有线程切换开销和竞态条件问题。与多进程不同，asyncio 可以轻松处理数万个并发连接。&#xA;核心概念 协程（Coroutine） 协程是可以暂停执行和恢复执行的函数，是 async/await 的基础：&#xA;import asyncio # 定义协程函数 async def say_hello(): print(&amp;#34;你好&amp;#34;) await asyncio.sleep(1) # 模拟 I/O 等待 print(&amp;#34;世界&amp;#34;) # 调用协程函数返回协程对象，不会执行 coro = say_hello() print(type(coro)) # &amp;lt;class &amp;#39;coroutine&amp;#39;&amp;gt; # 运行协程 asyncio.run(say_hello()) 关键区别：&#xA;普通函数调用：func() → 立即执行并返回结果 协程函数调用：async_func() → 返回协程对象，需要 await 或 asyncio.run await 关键字 await 用于等待一个 awaitable 对象（协程、Task、Future）完成：&#xA;import asyncio async def fetch_data(): print(&amp;#34;开始获取数据...&amp;#34;) await asyncio.</description>
    </item>
  </channel>
</rss>
