[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"$fhqqrKV5SbbZDCEpjY986X2Tc5ZODao8w75oV7fcte-Y":3,"$fJU-4tot_gC5fDkujNeoE-cGsdMy5V_KcdUXLuAnTFgw":16,"$f0TVfKNKSdMu0lIQ6bZcvSlvo-NOCXmagPx_gQN0yRgM":423},{"slug":4,"title":5,"description":6,"content":7,"content_html":8,"pub_date":9,"tags":10,"draft":15},"python-asyncio-practical","Python asyncio 实战：从回调地狱到协程优雅","asyncio 是 Python 异步编程的核心，搞懂 event loop、Task、gather 这些概念才能写出真正高效的异步代码。","# Python asyncio 实战：从回调地狱到协程优雅\n\n## 先搞清楚：该用哪种并发\n\n| 场景 | 推荐方案 |\n|------|---------|\n| I\u002FO 密集（网络请求、文件读写） | asyncio \u002F 多线程 |\n| CPU 密集（计算、图像处理） | 多进程（multiprocessing） |\n| 简单并发、兼容老代码 | 多线程（threading） |\n| 高性能异步 I\u002FO | asyncio |\n\nasyncio 的核心优势：**单线程处理大量并发 I\u002FO，内存开销远小于多线程**。\n\n## Event Loop 工作原理\n\n```\n┌─────────────────────────────────────────────┐\n│                Event Loop                    │\n│                                              │\n│  ┌──────────┐    ┌──────────┐    ┌────────┐ │\n│  │ Coroutine│    │  Task    │    │ Future │ │\n│  │(async def)│──▶│(Task包装 │──▶│(底层   │ │\n│  │          │    │ coroutine│    │ 结果   │ │\n│  └──────────┘    └──────────┘    └────────┘ │\n│                                              │\n│  等待 I\u002FO 时挂起 → 切换到其他任务 → I\u002FO 完成后恢复  │\n└─────────────────────────────────────────────┘\n```\n\n- **Coroutine**：`async def` 定义的函数，调用后返回协程对象\n- **Task**：对 coroutine 的封装，由 event loop 调度\n- **Future**：代表一个异步操作的最终结果\n\n## 基础语法\n\n```python\nimport asyncio\n\n# 定义协程\nasync def fetch_data(url: str) -> str:\n    print(f\"开始请求 {url}\")\n    await asyncio.sleep(1)  # 模拟 I\u002FO 等待\n    return f\"data from {url}\"\n\n# 运行协程\nasync def main():\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\")\n    print(result)\n\nasyncio.run(main())\n```\n\n## asyncio.gather()：并发执行\n\n```python\nimport asyncio\nimport time\n\nasync def task(name: str, delay: float) -> str:\n    await asyncio.sleep(delay)\n    return f\"{name} done\"\n\nasync def main():\n    start = time.time()\n\n    # 顺序执行：约 3 秒\n    # r1 = await task(\"A\", 1)\n    # r2 = await task(\"B\", 1)\n    # r3 = await task(\"C\", 1)\n\n    # 并发执行：约 1 秒\n    results = await asyncio.gather(\n        task(\"A\", 1),\n        task(\"B\", 1),\n        task(\"C\", 1),\n    )\n\n    print(results)  # ['A done', 'B done', 'C done']\n    print(f\"耗时: {time.time() - start:.2f}s\")  # 约 1.00s\n\nasyncio.run(main())\n```\n\n### gather() 异常处理\n\n```python\nasync def risky(name: str) -> str:\n    if name == \"B\":\n        raise ValueError(\"B failed!\")\n    return f\"{name} ok\"\n\nasync def main():\n    # return_exceptions=True：异常作为结果返回，不中断其他任务\n    results = await asyncio.gather(\n        risky(\"A\"),\n        risky(\"B\"),\n        risky(\"C\"),\n        return_exceptions=True,\n    )\n    for r in results:\n        if isinstance(r, Exception):\n            print(f\"Error: {r}\")\n        else:\n            print(f\"OK: {r}\")\n\nasyncio.run(main())\n```\n\n## create_task()：后台任务\n\n```python\nimport asyncio\n\nasync def background_job(n: int) -> None:\n    await asyncio.sleep(0.5)\n    print(f\"Job {n} complete\")\n\nasync def main():\n    # 创建任务后立即返回，任务在后台运行\n    t1 = asyncio.create_task(background_job(1))\n    t2 = asyncio.create_task(background_job(2))\n\n    print(\"做其他事情...\")\n    await asyncio.sleep(0.1)\n    print(\"继续做其他事情...\")\n\n    # 等待任务完成\n    await t1\n    await t2\n\nasyncio.run(main())\n```\n\n## asyncio.Queue：生产者消费者\n\n```python\nimport asyncio\n\nasync def producer(queue: asyncio.Queue, items: list[str]) -> None:\n    for item in items:\n        await queue.put(item)\n        print(f\"生产: {item}\")\n        await asyncio.sleep(0.1)\n    await queue.put(None)  # 终止信号\n\nasync def consumer(queue: asyncio.Queue, name: str) -> None:\n    while True:\n        item = await queue.get()\n        if item is None:\n            await queue.put(None)  # 传递终止信号给其他 consumer\n            break\n        print(f\"{name} 消费: {item}\")\n        await asyncio.sleep(0.3)\n        queue.task_done()\n\nasync def main():\n    queue: asyncio.Queue[str | None] = asyncio.Queue(maxsize=5)\n    items = [f\"task_{i}\" for i in range(6)]\n\n    await asyncio.gather(\n        producer(queue, items),\n        consumer(queue, \"Consumer-1\"),\n        consumer(queue, \"Consumer-2\"),\n    )\n\nasyncio.run(main())\n```\n\n## aiohttp：异步 HTTP 请求\n\n```python\nimport asyncio\nimport aiohttp  # pip install aiohttp\n\nasync def fetch(session: aiohttp.ClientSession, url: str) -> tuple[str, int]:\n    async with session.get(url) as resp:\n        return url, resp.status\n\nasync def fetch_all(urls: list[str]) -> list[tuple[str, int]]:\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch(session, url) for url in urls]\n        return await asyncio.gather(*tasks)\n\nasync def main():\n    urls = [\n        \"https:\u002F\u002Fhttpbin.org\u002Fget\",\n        \"https:\u002F\u002Fhttpbin.org\u002Fstatus\u002F200\",\n        \"https:\u002F\u002Fhttpbin.org\u002Fstatus\u002F404\",\n    ]\n    results = await fetch_all(urls)\n    for url, status in results:\n        print(f\"{status} - {url}\")\n\nasyncio.run(main())\n```\n\n## asyncio.Semaphore：限制并发数\n\n```python\nimport asyncio\nimport aiohttp\n\nasync def fetch_with_limit(\n    session: aiohttp.ClientSession,\n    url: str,\n    sem: asyncio.Semaphore,\n) -> str:\n    async with sem:  # 同时最多 10 个请求\n        async with session.get(url) as resp:\n            return await resp.text()\n\nasync def main():\n    urls = [f\"https:\u002F\u002Fhttpbin.org\u002Fget?n={i}\" for i in range(50)]\n    sem = asyncio.Semaphore(10)  # 并发上限 10\n\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch_with_limit(session, url, sem) for url in urls]\n        results = await asyncio.gather(*tasks)\n    print(f\"获取了 {len(results)} 个响应\")\n\nasyncio.run(main())\n```\n\n## 超时控制：asyncio.wait_for()\n\n```python\nimport asyncio\n\nasync def slow_operation() -> str:\n    await asyncio.sleep(5)\n    return \"done\"\n\nasync def main():\n    try:\n        result = await asyncio.wait_for(slow_operation(), timeout=2.0)\n        print(result)\n    except asyncio.TimeoutError:\n        print(\"操作超时！\")\n\nasyncio.run(main())\n```\n\n## 常见坑：在 async 里调用阻塞函数\n\n```python\nimport asyncio\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\n# ❌ 错误：阻塞整个 event loop\nasync def bad():\n    time.sleep(2)  # 阻塞！其他协程无法运行\n    return \"done\"\n\n# ✅ 正确：放到线程池里跑\nasync def good():\n    loop = asyncio.get_running_loop()\n    # 在线程池中运行阻塞函数\n    result = await loop.run_in_executor(None, time.sleep, 2)\n    return \"done\"\n\n# 或者用 asyncio.to_thread（Python 3.9+）\nasync def better():\n    await asyncio.to_thread(time.sleep, 2)\n    return \"done\"\n```\n\n## 实际案例：并发抓取 100 个 URL\n\n```python\nimport asyncio\nimport time\nimport aiohttp\nimport requests  # pip install requests\n\nURLS = [f\"https:\u002F\u002Fhttpbin.org\u002Fget?n={i}\" for i in range(20)]\n\n# 同步版本\ndef sync_fetch_all() -> None:\n    for url in URLS:\n        requests.get(url)\n\n# 异步版本\nasync def async_fetch_all() -> None:\n    sem = asyncio.Semaphore(10)\n\n    async def fetch(session: aiohttp.ClientSession, url: str) -> None:\n        async with sem:\n            async with session.get(url) as r:\n                await r.read()\n\n    async with aiohttp.ClientSession() as session:\n        await asyncio.gather(*[fetch(session, url) for url in URLS])\n\ndef main():\n    # 同步\n    t0 = time.time()\n    sync_fetch_all()\n    sync_time = time.time() - t0\n    print(f\"同步: {sync_time:.2f}s\")\n\n    # 异步\n    t0 = time.time()\n    asyncio.run(async_fetch_all())\n    async_time = time.time() - t0\n    print(f\"异步: {async_time:.2f}s\")\n    print(f\"加速比: {sync_time \u002F async_time:.1f}x\")\n\nif __name__ == \"__main__\":\n    main()\n# 典型输出：\n# 同步: 12.34s\n# 异步: 1.23s\n# 加速比: 10.0x\n```\n\n## 总结\n\n| API | 用途 |\n|-----|------|\n| `async def \u002F await` | 定义和等待协程 |\n| `asyncio.run()` | 程序入口，运行主协程 |\n| `asyncio.gather()` | 并发运行多个协程 |\n| `asyncio.create_task()` | 创建后台任务 |\n| `asyncio.Queue` | 生产者消费者 |\n| `asyncio.Semaphore` | 限制并发数 |\n| `asyncio.wait_for()` | 超时控制 |\n| `loop.run_in_executor()` | 阻塞函数异步化 |\n\nasyncio 适合 I\u002FO 密集型场景。CPU 密集型任务请用 `multiprocessing`，两者可以配合使用。\n","\u003Ch1>Python asyncio 实战：从回调地狱到协程优雅\u003C\u002Fh1>\n\u003Ch2 id=\"先搞清楚-该用哪种并发\">先搞清楚：该用哪种并发\u003C\u002Fh2>\n\u003Ctable>\n\u003Cthead>\n\u003Ctr>\n\u003Cth>场景\u003C\u002Fth>\n\u003Cth>推荐方案\u003C\u002Fth>\n\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\n\u003Ctd>I\u002FO 密集（网络请求、文件读写）\u003C\u002Ftd>\n\u003Ctd>asyncio \u002F 多线程\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>CPU 密集（计算、图像处理）\u003C\u002Ftd>\n\u003Ctd>多进程（multiprocessing）\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>简单并发、兼容老代码\u003C\u002Ftd>\n\u003Ctd>多线程（threading）\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>高性能异步 I\u002FO\u003C\u002Ftd>\n\u003Ctd>asyncio\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\u003Cp>asyncio 的核心优势：\u003Cstrong>单线程处理大量并发 I\u002FO，内存开销远小于多线程\u003C\u002Fstrong>。\u003C\u002Fp>\n\u003Ch2 id=\"event-loop-工作原理\">Event Loop 工作原理\u003C\u002Fh2>\n\u003Cpre>\u003Ccode>┌─────────────────────────────────────────────┐\n│                Event Loop                    │\n│                                              │\n│  ┌──────────┐    ┌──────────┐    ┌────────┐ │\n│  │ Coroutine│    │  Task    │    │ Future │ │\n│  │(async def)│──▶│(Task包装 │──▶│(底层   │ │\n│  │          │    │ coroutine│    │ 结果   │ │\n│  └──────────┘    └──────────┘    └────────┘ │\n│                                              │\n│  等待 I\u002FO 时挂起 → 切换到其他任务 → I\u002FO 完成后恢复  │\n└─────────────────────────────────────────────┘\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Cul>\n\u003Cli>\u003Cstrong>Coroutine\u003C\u002Fstrong>：\u003Ccode>async def\u003C\u002Fcode> 定义的函数，调用后返回协程对象\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Task\u003C\u002Fstrong>：对 coroutine 的封装，由 event loop 调度\u003C\u002Fli>\n\u003Cli>\u003Cstrong>Future\u003C\u002Fstrong>：代表一个异步操作的最终结果\u003C\u002Fli>\n\u003C\u002Ful>\n\u003Ch2 id=\"基础语法\">基础语法\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\n\n# 定义协程\nasync def fetch_data(url: str) -&gt; str:\n    print(f&quot;开始请求 {url}&quot;)\n    await asyncio.sleep(1)  # 模拟 I\u002FO 等待\n    return f&quot;data from {url}&quot;\n\n# 运行协程\nasync def main():\n    result = await fetch_data(&quot;https:\u002F\u002Fapi.example.com&quot;)\n    print(result)\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"asyncio-gather-并发执行\">asyncio.gather()：并发执行\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\nimport time\n\nasync def task(name: str, delay: float) -&gt; str:\n    await asyncio.sleep(delay)\n    return f&quot;{name} done&quot;\n\nasync def main():\n    start = time.time()\n\n    # 顺序执行：约 3 秒\n    # r1 = await task(&quot;A&quot;, 1)\n    # r2 = await task(&quot;B&quot;, 1)\n    # r3 = await task(&quot;C&quot;, 1)\n\n    # 并发执行：约 1 秒\n    results = await asyncio.gather(\n        task(&quot;A&quot;, 1),\n        task(&quot;B&quot;, 1),\n        task(&quot;C&quot;, 1),\n    )\n\n    print(results)  # ['A done', 'B done', 'C done']\n    print(f&quot;耗时: {time.time() - start:.2f}s&quot;)  # 约 1.00s\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch3 id=\"gather-异常处理\">gather() 异常处理\u003C\u002Fh3>\n\u003Cpre>\u003Ccode class=\"language-python\">async def risky(name: str) -&gt; str:\n    if name == &quot;B&quot;:\n        raise ValueError(&quot;B failed!&quot;)\n    return f&quot;{name} ok&quot;\n\nasync def main():\n    # return_exceptions=True：异常作为结果返回，不中断其他任务\n    results = await asyncio.gather(\n        risky(&quot;A&quot;),\n        risky(&quot;B&quot;),\n        risky(&quot;C&quot;),\n        return_exceptions=True,\n    )\n    for r in results:\n        if isinstance(r, Exception):\n            print(f&quot;Error: {r}&quot;)\n        else:\n            print(f&quot;OK: {r}&quot;)\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"create_task-后台任务\">create_task()：后台任务\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\n\nasync def background_job(n: int) -&gt; None:\n    await asyncio.sleep(0.5)\n    print(f&quot;Job {n} complete&quot;)\n\nasync def main():\n    # 创建任务后立即返回，任务在后台运行\n    t1 = asyncio.create_task(background_job(1))\n    t2 = asyncio.create_task(background_job(2))\n\n    print(&quot;做其他事情...&quot;)\n    await asyncio.sleep(0.1)\n    print(&quot;继续做其他事情...&quot;)\n\n    # 等待任务完成\n    await t1\n    await t2\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"asyncio-queue-生产者消费者\">asyncio.Queue：生产者消费者\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\n\nasync def producer(queue: asyncio.Queue, items: list[str]) -&gt; None:\n    for item in items:\n        await queue.put(item)\n        print(f&quot;生产: {item}&quot;)\n        await asyncio.sleep(0.1)\n    await queue.put(None)  # 终止信号\n\nasync def consumer(queue: asyncio.Queue, name: str) -&gt; None:\n    while True:\n        item = await queue.get()\n        if item is None:\n            await queue.put(None)  # 传递终止信号给其他 consumer\n            break\n        print(f&quot;{name} 消费: {item}&quot;)\n        await asyncio.sleep(0.3)\n        queue.task_done()\n\nasync def main():\n    queue: asyncio.Queue[str | None] = asyncio.Queue(maxsize=5)\n    items = [f&quot;task_{i}&quot; for i in range(6)]\n\n    await asyncio.gather(\n        producer(queue, items),\n        consumer(queue, &quot;Consumer-1&quot;),\n        consumer(queue, &quot;Consumer-2&quot;),\n    )\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"aiohttp-异步-http-请求\">aiohttp：异步 HTTP 请求\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\nimport aiohttp  # pip install aiohttp\n\nasync def fetch(session: aiohttp.ClientSession, url: str) -&gt; tuple[str, int]:\n    async with session.get(url) as resp:\n        return url, resp.status\n\nasync def fetch_all(urls: list[str]) -&gt; list[tuple[str, int]]:\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch(session, url) for url in urls]\n        return await asyncio.gather(*tasks)\n\nasync def main():\n    urls = [\n        &quot;https:\u002F\u002Fhttpbin.org\u002Fget&quot;,\n        &quot;https:\u002F\u002Fhttpbin.org\u002Fstatus\u002F200&quot;,\n        &quot;https:\u002F\u002Fhttpbin.org\u002Fstatus\u002F404&quot;,\n    ]\n    results = await fetch_all(urls)\n    for url, status in results:\n        print(f&quot;{status} - {url}&quot;)\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"asyncio-semaphore-限制并发数\">asyncio.Semaphore：限制并发数\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\nimport aiohttp\n\nasync def fetch_with_limit(\n    session: aiohttp.ClientSession,\n    url: str,\n    sem: asyncio.Semaphore,\n) -&gt; str:\n    async with sem:  # 同时最多 10 个请求\n        async with session.get(url) as resp:\n            return await resp.text()\n\nasync def main():\n    urls = [f&quot;https:\u002F\u002Fhttpbin.org\u002Fget?n={i}&quot; for i in range(50)]\n    sem = asyncio.Semaphore(10)  # 并发上限 10\n\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch_with_limit(session, url, sem) for url in urls]\n        results = await asyncio.gather(*tasks)\n    print(f&quot;获取了 {len(results)} 个响应&quot;)\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"超时控制-asyncio-wait_for\">超时控制：asyncio.wait_for()\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\n\nasync def slow_operation() -&gt; str:\n    await asyncio.sleep(5)\n    return &quot;done&quot;\n\nasync def main():\n    try:\n        result = await asyncio.wait_for(slow_operation(), timeout=2.0)\n        print(result)\n    except asyncio.TimeoutError:\n        print(&quot;操作超时！&quot;)\n\nasyncio.run(main())\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"常见坑-在-async-里调用阻塞函数\">常见坑：在 async 里调用阻塞函数\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\n# ❌ 错误：阻塞整个 event loop\nasync def bad():\n    time.sleep(2)  # 阻塞！其他协程无法运行\n    return &quot;done&quot;\n\n# ✅ 正确：放到线程池里跑\nasync def good():\n    loop = asyncio.get_running_loop()\n    # 在线程池中运行阻塞函数\n    result = await loop.run_in_executor(None, time.sleep, 2)\n    return &quot;done&quot;\n\n# 或者用 asyncio.to_thread（Python 3.9+）\nasync def better():\n    await asyncio.to_thread(time.sleep, 2)\n    return &quot;done&quot;\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"实际案例-并发抓取-100-个-url\">实际案例：并发抓取 100 个 URL\u003C\u002Fh2>\n\u003Cpre>\u003Ccode class=\"language-python\">import asyncio\nimport time\nimport aiohttp\nimport requests  # pip install requests\n\nURLS = [f&quot;https:\u002F\u002Fhttpbin.org\u002Fget?n={i}&quot; for i in range(20)]\n\n# 同步版本\ndef sync_fetch_all() -&gt; None:\n    for url in URLS:\n        requests.get(url)\n\n# 异步版本\nasync def async_fetch_all() -&gt; None:\n    sem = asyncio.Semaphore(10)\n\n    async def fetch(session: aiohttp.ClientSession, url: str) -&gt; None:\n        async with sem:\n            async with session.get(url) as r:\n                await r.read()\n\n    async with aiohttp.ClientSession() as session:\n        await asyncio.gather(*[fetch(session, url) for url in URLS])\n\ndef main():\n    # 同步\n    t0 = time.time()\n    sync_fetch_all()\n    sync_time = time.time() - t0\n    print(f&quot;同步: {sync_time:.2f}s&quot;)\n\n    # 异步\n    t0 = time.time()\n    asyncio.run(async_fetch_all())\n    async_time = time.time() - t0\n    print(f&quot;异步: {async_time:.2f}s&quot;)\n    print(f&quot;加速比: {sync_time \u002F async_time:.1f}x&quot;)\n\nif __name__ == &quot;__main__&quot;:\n    main()\n# 典型输出：\n# 同步: 12.34s\n# 异步: 1.23s\n# 加速比: 10.0x\n\u003C\u002Fcode>\u003C\u002Fpre>\n\u003Ch2 id=\"总结\">总结\u003C\u002Fh2>\n\u003Ctable>\n\u003Cthead>\n\u003Ctr>\n\u003Cth>API\u003C\u002Fth>\n\u003Cth>用途\u003C\u002Fth>\n\u003C\u002Ftr>\n\u003C\u002Fthead>\n\u003Ctbody>\n\u003Ctr>\n\u003Ctd>\u003Ccode>async def \u002F await\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>定义和等待协程\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>asyncio.run()\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>程序入口，运行主协程\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>asyncio.gather()\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>并发运行多个协程\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>asyncio.create_task()\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>创建后台任务\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>asyncio.Queue\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>生产者消费者\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>asyncio.Semaphore\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>限制并发数\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>asyncio.wait_for()\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>超时控制\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003Ctr>\n\u003Ctd>\u003Ccode>loop.run_in_executor()\u003C\u002Fcode>\u003C\u002Ftd>\n\u003Ctd>阻塞函数异步化\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftbody>\n\u003C\u002Ftable>\n\u003Cp>asyncio 适合 I\u002FO 密集型场景。CPU 密集型任务请用 \u003Ccode>multiprocessing\u003C\u002Fcode>，两者可以配合使用。\u003C\u002Fp>\n","2026-05-03",[11,12,13,14],"python","asyncio","并发","网络编程",false,[17,30,41,53,62,69,76,83,90,97,107,116,125,134,142,150,159,162,171,181,188,198,204,211,217,226,233,240,248,258,267,276,286,296,306,314,324,335,345,354,362,368,376,384,392,400,408,415],{"slug":18,"title":19,"description":20,"pub_date":21,"tags":22,"draft":15,"word_count":29},"ide-skills-guide","Agent Skills 完全指南：21 款第三方 Skill 深度评测与使用心得","全面评测 21 款第三方 Agent Skills，涵盖 Vue 生态、前端设计、构建工具、实用工具四大分类。从安装配置到实际使用场景，带你了解每个 Skill 的功能特点、最佳实践与使用心得。","2026-06-15",[23,24,25,26,27,28],"agent","skills","AI","效率工具","前端","Vue",4169,{"slug":31,"title":32,"description":33,"pub_date":34,"tags":35,"draft":15,"word_count":40},"linux-kernel-skeleton-struct-funcptr-container_of","Linux 内核骨架：struct、函数指针与 container_of","读懂 Linux 内核源码的三件套：巨大的 struct 组合代替继承、函数指针表实现虚派发、container_of 宏从嵌入成员找回完整对象。","2026-05-09",[36,37,38,39],"linux","kernel","C","container_of",1369,{"slug":42,"title":43,"description":44,"pub_date":45,"tags":46,"draft":15,"word_count":52},"astro-complete-guide-2025","Astro 5 深度剖析：Islands 架构原理、构建优化与 Cloudflare Workers 边缘部署","从编译器视角解析 Astro 5 的 Islands 架构实现原理，Content Layer API 的 Vite 插件机制，Server Islands 的流式渲染，以及如何在 Cloudflare Workers + D1 边缘环境下榨干性能。","2026-05-08",[47,48,49,50,51],"astro","frontend","cloudflare","performance","architecture",3663,{"slug":54,"title":55,"description":56,"pub_date":9,"tags":57,"draft":15,"word_count":61},"llm-prompt-engineering","Prompt Engineering 实战：让 LLM 真正听话的技巧","System prompt 怎么写、Few-shot 怎么设计、Chain-of-Thought 原理，以及常见失败模式和调试方法。",[58,59,60],"ai","llm","工程实践",1723,{"slug":63,"title":64,"description":65,"pub_date":9,"tags":66,"draft":15,"word_count":68},"rag-system-design","RAG 系统设计：从 naive 到 production-ready","Retrieval-Augmented Generation 不只是「向量数据库 + LLM」，分块策略、召回质量、重排序、缓存才是工程核心。",[58,67,59,60],"rag",1613,{"slug":70,"title":71,"description":72,"pub_date":9,"tags":73,"draft":15,"word_count":75},"git-advanced-workflow","Git 进阶工作流：rebase、cherry-pick、bisect 的正确使用","merge 会了，但 rebase 总搞错？bisect 找 bug 提交？interactive rebase 整理历史？这篇一次说清楚。",[74,60],"git",1396,{"slug":77,"title":78,"description":79,"pub_date":9,"tags":80,"draft":15,"word_count":82},"docker-practical-guide","Docker 实战：从会用到用好","会 docker run 不够，Dockerfile 最佳实践、多阶段构建、Compose 编排、镜像瘦身才是日常真正需要的。",[81,36,60],"docker",1268,{"slug":84,"title":85,"description":86,"pub_date":9,"tags":87,"draft":15,"word_count":89},"anthropics-skills-guide","anthropics\u002Fskills：Anthropic 官方 Agent Skills 仓库解析","Anthropic 官方开源的 Agent Skills 标准仓库，127k stars，解析 SKILL.md 规范、17 个示例 skill 的设计模式，以及如何在 Claude Code \u002F Claude.ai \u002F API 中使用",[58,88,23,24],"Claude",2090,{"slug":91,"title":92,"description":93,"pub_date":9,"tags":94,"draft":15,"word_count":96},"karpathy-claude-code-guidelines","Karpathy 的 LLM 编码批评与 CLAUDE.md 最佳实践","基于 Andrej Karpathy 对 LLM 编程助手的观察，forrestchang 提炼出一个 CLAUDE.md 文件，4 条原则解决 AI 编码的典型失控问题：乱猜假设、过度设计、乱改代码、目标不清",[58,88,95,60],"Claude Code",2699,{"slug":98,"title":99,"description":100,"pub_date":9,"tags":101,"draft":15,"word_count":106},"typescript-advanced-patterns","TypeScript 高级模式：让类型系统为你工作","基础 TS 会了但类型总是 any？条件类型、映射类型、模板字面量类型、infer 关键字才是 TS 的真正威力。",[102,103,104,105],"typescript","类型系统","前端工程","高级模式",1419,{"slug":108,"title":109,"description":110,"pub_date":9,"tags":111,"draft":15,"word_count":115},"linux-performance-tuning","Linux 性能调优实战：从 top 到 perf 的完整工具链","遇到性能问题不知道从哪下手？这篇建立系统化的排查思路，从 CPU\u002F内存\u002FIO\u002F网络逐层分析。",[36,112,113,114],"性能","运维","系统编程",1524,{"slug":117,"title":118,"description":119,"pub_date":9,"tags":120,"draft":15,"word_count":124},"python-functional-programming","Python 函数式编程：map\u002Ffilter\u002Freduce 之外","Python 不是纯函数式语言，但 functools、itertools、偏函数、闭包这些工具用好了能让代码简洁一个量级。",[11,121,122,123],"函数式","闭包","装饰器",1867,{"slug":126,"title":127,"description":128,"pub_date":9,"tags":129,"draft":15,"word_count":133},"python-oop-guide","Python 面向对象：__init__ 之外你需要知道的","Python OOP 不只是 class + __init__，魔术方法、描述符、元类才是真正的武器。",[11,130,131,132],"OOP","面向对象","魔术方法",1792,{"slug":135,"title":136,"description":137,"pub_date":9,"tags":138,"draft":15,"word_count":141},"python-data-structures","Python 内置数据结构深度解析","list、dict、set、tuple 不只是数据容器，搞懂它们的底层实现和时间复杂度，才能写出高性能 Python。",[11,139,112,140],"数据结构","算法",1517,{"slug":143,"title":144,"description":145,"pub_date":9,"tags":146,"draft":15,"word_count":149},"python-basics-quick-start","Python 快速上手：写给有编程基础的人","已经会其他语言，想快速掌握 Python 的语法特性和思维方式，这篇是捷径。",[11,147,148],"入门","基础",1607,{"slug":151,"title":152,"description":153,"pub_date":9,"tags":154,"draft":15,"word_count":158},"python-dataclass-pydantic","Python dataclass vs Pydantic：数据类选型指南","dataclass 是标准库的轻量选择，Pydantic v2 是带验证的重武器，什么时候用哪个，这篇说清楚。",[11,155,156,157],"dataclass","pydantic","数据验证",1323,{"slug":4,"title":5,"description":6,"pub_date":9,"tags":160,"draft":15,"word_count":161},[11,12,13,14],1258,{"slug":163,"title":164,"description":165,"pub_date":9,"tags":166,"draft":15,"word_count":170},"python-type-hints-guide","Python 类型注解完全指南：从入门到实践","Python 3.5+ 引入类型注解，配合 mypy\u002Fpyright 让 Python 也能享受静态类型检查的好处。",[11,167,168,169],"typescript-style","type-hints","工具链",1102,{"slug":172,"title":173,"description":174,"pub_date":175,"tags":176,"draft":15,"word_count":180},"pwa-install-update-button","PWA 踩坑：为什么安装按钮从来不出现","从 beforeinstallprompt 到 Service Worker waiting，把 PWA 的安装与更新提示真正做对","2026-05-02",[177,178,179],"pwa","javascript","web",1683,{"slug":182,"title":183,"description":184,"pub_date":185,"tags":186,"draft":15,"word_count":187},"openclaw-vs-hermes-agent","OpenClaw vs Hermes Agent：两个本地优先 Agent 的设计差异","OpenClaw（Novita AI）和 Hermes Agent（Nous Research）都是本地运行的个人 AI Agent，但在记忆系统、技能学习、运行环境和模型生态上走了不同的路。深入对比两种架构的核心差异。","2026-05-01",[58,23,59],1679,{"slug":189,"title":190,"description":191,"pub_date":185,"tags":192,"draft":15,"word_count":197},"cpp-random-design-patterns","C++ 设计模式实战：RAII、观察者、工厂","用现代 C++（C++17\u002F20）实现三种高频设计模式：RAII 资源管理、观察者模式事件系统、工厂模式插件架构。每种模式给出问题场景、实现代码和真实工程案例。",[193,194,195,196],"cpp","设计模式","c++17","工程",2613,{"slug":199,"title":200,"description":201,"pub_date":185,"tags":202,"draft":15,"word_count":203},"data-structures-fundamentals","数据结构基础：从数组到红黑树","系统梳理常用数据结构的核心原理、时间复杂度和适用场景。数组、链表、栈、队列、哈希表、二叉树、堆、图，每种结构附实现要点和 C++ 代码片段。",[139,140,193,148],3004,{"slug":205,"title":206,"description":207,"pub_date":208,"tags":209,"draft":15,"word_count":210},"ai-agent-what-is","什么是 AI Agent？从 LLM 到自主执行","LLM 本身是无状态问答机，Agent 是什么让它’动’起来的？本文深入解析 Agent 的四个核心能力、ReAct 框架、工具调用原理，以及主流框架横向对比。","2026-04-30",[58,23,59],2116,{"slug":212,"title":213,"description":214,"pub_date":208,"tags":215,"draft":15,"word_count":216},"ai-agent-memory","AI Agent 的记忆系统：从上下文窗口到长期记忆","深入拆解 AI Agent 的四种记忆类型、上下文窗口压缩策略、RAG 向量检索原理，以及三种典型失败模式和工程选型建议。",[58,23,67],2052,{"slug":218,"title":219,"description":220,"pub_date":208,"tags":221,"draft":15,"word_count":225},"network-proxy-vpn-guide","代理与翻墙技术原理：从 HTTP 代理到现代协议","深入解析代理与 VPN 的本质区别，梳理从 SOCKS5 到 Shadowsocks、V2Ray\u002FXray、Hysteria2 的协议演进，以及机场订阅的技术本质。",[222,223,224],"网络","代理","协议",2148,{"slug":227,"title":228,"description":229,"pub_date":208,"tags":230,"draft":15,"word_count":149},"algorithm-binary-search","二分查找：永远写不对？记住这个模板","彻底搞清楚二分查找的边界问题：闭区间和左闭右开两套模板、三道经典 LeetCode 题目完整 C++ 实现，以及二分答案的进阶思路。",[140,231,232,193],"二分查找","leetcode",{"slug":234,"title":235,"description":236,"pub_date":208,"tags":237,"draft":15,"word_count":239},"algorithm-sliding-window","滑动窗口算法：从暴力到 O(n) 的思维跃迁","系统讲解滑动窗口算法的核心模板、适用题型，配合三道经典 LeetCode 题目的完整 C++ 实现，彻底理解双指针收缩思路。",[140,238,232,193],"滑动窗口",1943,{"slug":241,"title":242,"description":243,"pub_date":208,"tags":244,"draft":15,"word_count":247},"network-clash-config","Clash \u002F Mihomo 配置详解：规则、策略组与分流","深入解析 Clash\u002FMihomo 的核心配置结构，包括代理节点、策略组类型、规则优先级、DNS fake-ip 模式，以及一份实用的完整配置模板。",[222,245,223,246],"clash","配置",1292,{"slug":249,"title":250,"description":251,"pub_date":252,"tags":253,"draft":15,"word_count":257},"hid-hotplug","HID 设备热插拔检测：从 udev 到 node-hid","在 Linux 上用 node-hid + usb 库实现可靠的 USB HID 设备热插拔检测，踩坑记录","2026-04-28",[193,254,36,255,256],"hid","nodejs","electron",2039,{"slug":259,"title":260,"description":261,"pub_date":262,"tags":263,"draft":15,"word_count":266},"electron-ipc-types","Electron IPC 类型安全：从 any 到完全类型化","用 TypeScript 泛型封装 Electron IPC，彻底消灭 any，preload 契约集中管理","2026-04-25",[256,102,264,265],"ipc","vue",1446,{"slug":268,"title":269,"description":270,"pub_date":271,"tags":272,"draft":15,"word_count":275},"element-plus-popover-hide","手动关闭多个 el-popover（不用 v-model:visible）","通过 ref + Reflect.get 调用 hide() 方法手动关闭 Element Plus Popover，解释 Vue3 Proxy 导致无法直接调用实例方法的原因。","2024-10-25",[265,273,274],"element-plus","vue3",1321,{"slug":277,"title":278,"description":279,"pub_date":280,"tags":281,"draft":15,"word_count":285},"vite-vue3-ts-elementplus-pinia","用 Vite+（vp）从零搭建 Vue3 + TypeScript + Element Plus + Pinia + Vue Router","使用 Vite+ 统一工具链（vp）一条命令搭建 Vue3 全家桶，涵盖按需导入、Pinia store、路由配置，以及常见坑的解决方案。","2024-08-27",[265,282,102,273,283,284],"vite","pinia","vite-plus",1960,{"slug":287,"title":288,"description":289,"pub_date":290,"tags":291,"draft":15,"word_count":295},"cef-lnk2038-iterator-debug-level","CEF LNK2038：解决 _ITERATOR_DEBUG_LEVEL 不匹配错误","分析 CEF（Chromium Embedded Framework）集成时出现的 LNK2038 _ITERATOR_DEBUG_LEVEL 链接错误，从根本原因到解决方案的完整指南。","2024-05-07",[193,292,293,294],"CEF","Visual Studio","链接错误",1509,{"slug":297,"title":298,"description":299,"pub_date":300,"tags":301,"draft":15,"word_count":305},"npm-electron-install-fix","彻底解决 npm 安装 Electron 失败的问题","分析 npm install electron 失败的根本原因（下载二进制超时\u002F被墙），通过国内镜像（npmmirror）彻底解决，并介绍多种备选方案和常见错误排查。","2024-03-01",[256,302,303,304],"npm","前端工具链","国内镜像",1494,{"slug":307,"title":308,"description":309,"pub_date":310,"tags":311,"draft":15,"word_count":313},"git-out-of-memory","解决 git 报错：Fatal: Out of memory, malloc failed","分析 git 大仓库操作时出现 Out of memory malloc failed 的根本原因，通过调整 pack.windowMemory、http.postBuffer 和 git repack 彻底解决。","2024-01-31",[74,36,312],"工具",2244,{"slug":315,"title":316,"description":317,"pub_date":318,"tags":319,"draft":15,"word_count":323},"vmware-tools-install","在 VMware 虚拟机中安装 open-vm-tools 完整指南","详解 VMware Tools 的作用、open-vm-tools 与官方 VMware Tools 的区别，以及在 Ubuntu 虚拟机中安装并生效的完整步骤和常见问题排查。","2023-11-21",[320,36,321,322],"VMware","Ubuntu","虚拟机",2523,{"slug":325,"title":326,"description":327,"pub_date":328,"tags":329,"draft":15,"word_count":334},"load-balancing-algorithms","负载均衡算法完全指南：从轮询到一致性哈希","系统梳理静态与动态负载均衡算法，涵盖轮询、随机、权重、IP Hash、一致性 Hash、最少连接、最快响应等，并对比 Nginx、Dubbo、Spring Cloud LoadBalancer 的实现差异。","2023-11-15",[330,331,332,333],"分布式","负载均衡","Nginx","微服务",1764,{"slug":336,"title":337,"description":338,"pub_date":339,"tags":340,"draft":15,"word_count":344},"win-cw2a-ca2w","ATL 字符串转换：CW2A 与 CA2W 完全指南","详解 ATL 宏 CW2A\u002FCA2W 在 Unicode 与 ANSI 之间的字符串转换用法、头文件依赖、USES_CONVERSION 宏的作用与常见陷阱。","2023-06-09",[193,341,342,343],"windows","ATL","字符串",1665,{"slug":346,"title":347,"description":348,"pub_date":339,"tags":349,"draft":15,"word_count":353},"csharp-sendmessage-cpp","C# 通过 SendMessage 向 C++ 窗口发送消息与字符串","使用 P\u002FInvoke 调用 user32.dll 的 SendMessage，从 C# 发送自定义 WM_USER 消息及字符串指针给 C++ 原生窗口，并在 C++ 侧正确接收和转换。",[350,193,341,351,352],"C#","互操作","PInvoke",1554,{"slug":355,"title":356,"description":357,"pub_date":358,"tags":359,"draft":15,"word_count":361},"win-postmessage-vector","Windows PostMessage 跨线程传递 std::vector 指针","通过 PostMessage 在 Windows 消息队列中传递 std::vector 指针，使用 reinterpret_cast 将指针装入 LPARAM，并在接收方正确释放内存。","2023-05-26",[193,341,360],"WinAPI",1823,{"slug":363,"title":364,"description":365,"pub_date":358,"tags":366,"draft":15,"word_count":367},"exe-dll-single-package","将 EXE 和 DLL 打包成单一可执行文件","介绍两种将 exe 和依赖 dll 打包成单文件的方案：Enigma Virtual Box 和 WinRAR 自解压，适合发布 Windows 桌面程序时简化分发流程。",[341,193,312],1619,{"slug":369,"title":370,"description":371,"pub_date":358,"tags":372,"draft":15,"word_count":375},"cpp-random-mt19937","C++ 现代随机数生成：用 mt19937 彻底告别 rand()","深入讲解为什么 rand() 不够用，以及如何用 C++11 的 \u003Crandom> 库正确生成高质量随机数，涵盖 mt19937、各种分布和线程安全。",[193,373,374],"c++11","random",1549,{"slug":377,"title":378,"description":379,"pub_date":380,"tags":381,"draft":15,"word_count":383},"win-startup-registry","C++ 实现程序开机自启动：注册表方式详解","通过操作 Windows 注册表 Run 键实现程序开机自启动，包括 HKCU 与 HKLM 区别、完整封装代码、工作目录问题和 UAC 权限处理。","2022-12-26",[341,193,382],"registry",1201,{"slug":385,"title":386,"description":387,"pub_date":388,"tags":389,"draft":15,"word_count":391},"mfc-cstring-wparam","MFC 中 CString 与 WPARAM 之间的转换","详解 MFC 消息传递中 CString 无法直接强转为 WPARAM 的原因，以及两种正确的转换方案，并介绍结构体指针传递的正确姿势。","2022-11-25",[390,193,341],"mfc",1546,{"slug":393,"title":394,"description":395,"pub_date":396,"tags":397,"draft":15,"word_count":399},"duilib-static-build","正确编译 Duilib 静态库：避免 ATL 依赖和链接错误","详解如何用 DuiLib_Static.vcxproj 编译 Duilib 静态库，解决 VARIANT 未定义、Unicode 配置不匹配和 ATL 依赖等常见问题。","2022-08-24",[193,398,341,390],"duilib",2639,{"slug":401,"title":402,"description":403,"pub_date":404,"tags":405,"draft":15,"word_count":407},"mfc-dpi-adaptive","MFC 界面自适应不同分辨率","MFC 对话框程序实现控件和字体随分辨率自动缩放的完整方案，附 DPI Awareness 配置说明","2022-08-17",[390,193,341,406],"dpi",1414,{"slug":409,"title":410,"description":411,"pub_date":412,"tags":413,"draft":15,"word_count":414},"mfc-drag-window","MFC 无标题栏窗口客户区拖动：三种方法对比","MFC 对话框去掉标题栏后如何实现拖动移动窗口，三种方案完整实现与适用场景分析","2022-08-16",[390,193,341],1633,{"slug":416,"title":417,"description":418,"pub_date":419,"tags":420,"draft":15,"word_count":422},"algorithm-number-complement","整数的补数：位运算掩码解法","LeetCode 476 题，用掩码 XOR 实现整数补数，附 C++\u002FPython\u002FJava 三种实现及补数与补码的区别","2021-03-08",[140,421,232],"位运算",1374,[]]