惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
罗磊的独立博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
博客园 - 司徒正美
博客园 - 叶小钗
T
Tailwind CSS Blog
博客园 - Franky
V
V2EX
有赞技术团队
有赞技术团队
美团技术团队
雷峰网
雷峰网
爱范儿
爱范儿
Jina AI
Jina AI
D
DataBreaches.Net
H
Help Net Security
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Is asyncio Really Better Than Multithreading? I Tested 10...
BAOFUFAN · 2026-05-01 · via DEV Community

BAOFUFAN

Last month, the data platform I maintain suddenly got a new requirement: run health checks against 100+ downstream services. Each endpoint averages 200ms, and the whole check had to finish within 5 seconds. Without thinking twice, I fired up 100 threads. The thread-switching overhead immediately maxed out the CPU, and the response time shot past 8 seconds. My ops teammate dropped three question marks in the group chat.

That moment forced me to seriously re‑examine asyncio. I used to think async programming had a steep learning curve and was a magnet for bugs, but after a thorough benchmark I can only say: for IO‑bound workloads, asyncio and multithreading aren’t even in the same league. Here’s the full breakdown of running the same task with three different strategies—synchronous, multithreaded, and asyncio—head‑to‑head.

Test scenario: 100 HTTP requests, each with 200 ms latency

We spun up a mock downstream service with FastAPI. The /health endpoint deliberately sleeps for 200 ms and then returns {"status": "ok"}. The client fires 100 concurrent requests using three different approaches, and we measure total elapsed time and resource usage.

Approach 1: Synchronous sequential — predictably slow

# sync_demo.py — 同步请求,一个接一个
import time
import requests

URLS = [f"http://localhost:8000/health" for _ in range(100)]

def check_sync():
    results = []
    for url in URLS:
        resp = requests.get(url, timeout=5)
        results.append(resp.json())
    return results

if __name__ == "__main__":
    start = time.perf_counter()
    check_sync()
    elapsed = time.perf_counter() - start
    print(f"同步耗时: {elapsed:.2f}s")   # 20.3s 左右

Enter fullscreen mode Exit fullscreen mode

Unsurprisingly, 100 × 200 ms = 20 seconds. The thread spends all its time waiting for network I/O while the CPU sits nearly idle. That’s with only 100 requests; at 1 000 the system would be effectively frozen for three minutes with zero concurrency.

Approach 2: Multithreading — looks concurrent, full of traps

# thread_demo.py — 100 个线程并发
import time
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed

URLS = [f"http://localhost:8000/health" for _ in range(100)]

def fetch(url):
    return requests.get(url, timeout=5).json()

def check_thread():
    results = []
    with ThreadPoolExecutor(max_workers=100) as executor:
        futures = {executor.submit(fetch, url): url for url in URLS}
        for future in as_completed(futures):
            results.append(future.result())
    return results

if __name__ == "__main__":
    start = time.perf_counter()
    check_thread()
    elapsed = time.perf_counter() - start
    print(f"多线程耗时: {elapsed:.2f}s")  # 第一次 8.5s,后来波动在 3~6s

Enter fullscreen mode Exit fullscreen mode

The first run took 8.5 seconds, with CPU usage instantly spiking to 90%. Python’s GIL is released during I/O, but creating 100 threads, the constant context switching, and lock contention add enormous overhead. When I dialled max_workers down to 30, the time dropped to 2.1 seconds and the CPU settled down—but that turns into “tuning by gut feeling,” and as soon as the thread count rises, the system becomes unstable again.

There’s an even sneakier trap: the requests library isn’t the most thread‑safe choice, its connection‑pool reuse is limited, and occasionally it throws a ConnectionResetError that’s a nightmare to debug.

Approach 3: asyncio + aiohttp — so smooth it feels like cheating

# async_demo.py — 使用 asyncio 和 aiohttp 并发请求
import asyncio
import time
import aiohttp

URLS = [f"http://localhost:8000/health" for _ in range(100)]

async def fetch(session, url):
    try:
        async with session.get(url, timeout=5) as resp:
            return await resp.json()
    except Exception as e:
        return {"error": str(e)}

async def check_async():
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in URLS]
        results = await asyncio.gather(*tasks)
    return results

if __name__ == "__main__":
    start = time.perf_counter()
    asyncio.run(check_async())
    elapsed = time.perf_counter() - start
    print(f"asyncio 耗时: {elapsed:.2f}s")  # 稳定在 0.45~0.60s

Enter fullscreen mode Exit fullscreen mode

All 100 tasks are scheduled inside a single event loop and dispatched asynchronously. The total elapsed time is determined only by the slowest I/O call, consistently coming in under 0.6 seconds. CPU usage never topped 15%, and memory usage stayed almost perfectly flat. When my boss saw the results on the monitoring dashboard he asked if I had secretly added more servers—turns out I just rewrote the code with async/await.

Pitfalls & takeaways: I fell into all three of these traps

  1. Mixing synchronous code into a coroutine instantly kills performance. At first I put requests.get() directly inside an async def and...