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

推荐订阅源

Help Net Security
Help Net Security
Recent Announcements
Recent Announcements
A
About on SuperTechFans
N
News and Events Feed by Topic
I
Intezer
B
Blog
GbyAI
GbyAI
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Project Zero
Project Zero
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
阮一峰的网络日志
阮一峰的网络日志
T
Troy Hunt's Blog
TaoSecurity Blog
TaoSecurity Blog
IT之家
IT之家
MyScale Blog
MyScale Blog
The Register - Security
The Register - Security
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
酷 壳 – CoolShell
酷 壳 – CoolShell
Stack Overflow Blog
Stack Overflow Blog
P
Privacy & Cybersecurity Law Blog
S
Secure Thoughts
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
Hacker News - Newest:
Hacker News - Newest: "LLM"
G
Google Developers Blog
罗磊的独立博客
博客园 - 聂微东
G
GRAHAM CLULEY
AWS News Blog
AWS News Blog
Google Online Security Blog
Google Online Security Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hacker News: Front Page
C
Check Point Blog
L
Lohrmann on Cybersecurity
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Spread Privacy
Spread Privacy
O
OpenAI News
T
Tor Project blog
P
Privacy International News Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Attack and Defense Labs
Attack and Defense Labs
L
LINUX DO - 最新话题
Forbes - Security
Forbes - Security
云风的 BLOG
云风的 BLOG
C
Cisco Blogs
S
Securelist
博客园_首页

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Python asyncio
MEROLINE LIZ · 2026-05-13 · via DEV Community

One of the most potent standard library modules in Python is called "asyncio," but it's also one of the most misunderstood. When asyncio might work better, developers reach for threads or processes, or they use async/await everywhere without knowing what it truly does.

This article discusses the useful patterns you'll utilize on a daily basis after building a real mental model from the ground up.

The Core Problem: I/O Is Slow

Your CPU can execute billions of operations per second. A network request takes 50–500 milliseconds. Reading from disk takes milliseconds. If your code does this:

result1 = fetch_from_database(query1)  # wait 100ms
result2 = call_external_api(url)       # wait 200ms
result3 = read_large_file(path)        # wait 50ms
# Total: ~350ms

Enter fullscreen mode Exit fullscreen mode

Your computers brain, the CPU is not doing anything for most of the time. It is just waiting around.

Threading is a way to make use of this time. It does this by doing things at the same time. But Threading has some problems. It needs memory it has to switch between tasks and it can have bugs. There is also something called the GIL.

asyncio does things differently. Of doing many things at the same time it does one thing at a time.. When the thing it is doing is waiting, asyncio switches, to something else. This way, asyncio only uses one thread. It works together with the tasks so it does not use up too many resources.

The Event Loop

The thing about asyncio is that it is about the event loop. This event loop is like a scheduler. Here is what it does:

  1. It runs a coroutine until it gets to an await.
  2. Then it sets up the I/O operation.
  3. After that the event loop moves on, to another coroutine.
  4. The event loop comes back when the I/O operation is finished.
import asyncio

async def main():
    print("Start")
    await asyncio.sleep(1)  # "I'm waiting — go run something else"
    print("Done")

asyncio.run(main())  # Create an event loop and run main()

Enter fullscreen mode Exit fullscreen mode

asyncio.run() is the modern entry point (Python 3.7+). It creates an event loop, runs your coroutine, and cleans up.

Coroutines: async def and await

A coroutine is a kind of function that you define with async def.
When you call it it does not start running away. Instead it gives you a coroutine object. You have to use await or schedule it to make it run. The coroutine only starts when you do one of these things. You have to tell it to go it won't go on its own. It needs await to begin.

import asyncio

async def greet(name: str):
    print(f"Hello, {name}")
    await asyncio.sleep(0.5)
    print(f"Goodbye, {name}")

async def main():
    # This runs sequentially — each greet waits for the previous to finish
    await greet("Alice")
    await greet("Bob")

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Hello, Alice
Goodbye, Alice
Hello, Bob
Goodbye, Bob

Enter fullscreen mode Exit fullscreen mode

Sequential, not concurrent. To get concurrency, you need asyncio.gather() or tasks.

asyncio.gather(): Run Coroutines Concurrently

import asyncio

async def fetch_user(user_id: int):
    print(f"Fetching user {user_id}...")
    await asyncio.sleep(1)  # Simulate network call
    return {"id": user_id, "name": f"User {user_id}"}

async def main():
    # Run all three concurrently — total time ~1s, not ~3s
    results = await asyncio.gather(
        fetch_user(1),
        fetch_user(2),
        fetch_user(3),
    )
    print(results)

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Fetching user 1...
Fetching user 2...
Fetching user 3...
[{'id': 1, ...}, {'id': 2, ...}, {'id': 3, ...}]

Enter fullscreen mode Exit fullscreen mode

All three started immediately; all three finished in ~1 second total.

Handling Errors in gather()

results = await asyncio.gather(
    fetch_user(1),
    fetch_user(2),
    fetch_user(999),
    return_exceptions=True,  # Don't raise — return exceptions as values
)

for result in results:
    if isinstance(result, Exception):
        print(f"Error: {result}")
    else:
        print(result)

Enter fullscreen mode Exit fullscreen mode

Tasks: Fire and Don't Wait

asyncio.create_task() schedules a coroutine to run concurrently without immediately awaiting it.

import asyncio

async def background_job(name: str, delay: float):
    await asyncio.sleep(delay)
    print(f"{name} completed after {delay}s")

async def main():
    # Schedule tasks without waiting for them
    task1 = asyncio.create_task(background_job("Job A", 2))
    task2 = asyncio.create_task(background_job("Job B", 1))

    print("Tasks started, doing other work...")
    await asyncio.sleep(0.5)
    print("Still doing other work...")

    # Wait for both tasks to finish
    await task1
    await task2
    print("All done")

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Tasks started, doing other work...
Still doing other work...
Job B completed after 1s
Job A completed after 2s
All done

Enter fullscreen mode Exit fullscreen mode

asyncio.wait() and as_completed()

More control over how you wait for multiple tasks:

import asyncio

async def slow_operation(n: int):
    await asyncio.sleep(n * 0.5)
    return n * 10

async def main():
    tasks = [asyncio.create_task(slow_operation(i)) for i in range(1, 5)]

    # Process results as they complete (not in order)
    for coro in asyncio.as_completed(tasks):
        result = await coro
        print(f"Got result: {result}")

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Got result: 10   ← task 1 finished first
Got result: 20
Got result: 30
Got result: 40

Enter fullscreen mode Exit fullscreen mode

Timeouts

import asyncio

async def slow_api_call():
    await asyncio.sleep(10)  # Takes forever
    return {"data": "..."}

async def main():
    try:
        # Raise TimeoutError if it takes more than 2 seconds
        result = await asyncio.wait_for(slow_api_call(), timeout=2.0)
    except asyncio.TimeoutError:
        print("Request timed out")

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Python 3.11+ adds asyncio.timeout() as a context manager:

async def main():
    try:
        async with asyncio.timeout(2.0):
            result = await slow_api_call()
            other_result = await another_call()
    except asyncio.TimeoutError:
        print("Timed out")

Enter fullscreen mode Exit fullscreen mode

Queues: Producer-Consumer Pattern

asyncio.Queue is perfect for worker pool patterns:

import asyncio
import random

async def producer(queue: asyncio.Queue, num_items: int):
    for i in range(num_items):
        await asyncio.sleep(random.uniform(0.1, 0.5))
        item = f"task_{i}"
        await queue.put(item)
        print(f"Produced: {item}")
    # Signal workers to stop
    for _ in range(3):  # one sentinel per worker
        await queue.put(None)

async def worker(name: str, queue: asyncio.Queue):
    while True:
        item = await queue.get()
        if item is None:
            break
        print(f"  {name} processing {item}")
        await asyncio.sleep(0.3)  # simulate work
        queue.task_done()
    print(f"  {name} shutting down")

async def main():
    queue = asyncio.Queue(maxsize=5)  # Buffer of 5 items

    # Start 3 workers
    workers = [
        asyncio.create_task(worker(f"Worker-{i}", queue))
        for i in range(3)
    ]

    await producer(queue, 10)
    await asyncio.gather(*workers)

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Semaphores: Limit Concurrency

When you have 1000 URLs to fetch but don't want to hammer a server with 1000 simultaneous connections:

import asyncio
import httpx

async def fetch(client: httpx.AsyncClient, url: str, semaphore: asyncio.Semaphore):
    async with semaphore:  # Only N coroutines can enter at once
        response = await client.get(url)
        return response.status_code

async def main():
    urls = [f"https://httpbin.org/delay/1?n={i}" for i in range(20)]
    semaphore = asyncio.Semaphore(5)  # Max 5 concurrent requests

    async with httpx.AsyncClient() as client:
        tasks = [fetch(client, url, semaphore) for url in urls]
        results = await asyncio.gather(*tasks)

    print(results)

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Locks and Synchronization

When multiple coroutines access shared state:

import asyncio

class Counter:
    def __init__(self):
        self.value = 0
        self._lock = asyncio.Lock()

    async def increment(self):
        async with self._lock:
            current = self.value
            await asyncio.sleep(0)  # Yield to event loop (simulate real work)
            self.value = current + 1

async def main():
    counter = Counter()
    tasks = [asyncio.create_task(counter.increment()) for _ in range(100)]
    await asyncio.gather(*tasks)
    print(f"Final count: {counter.value}")  # 100, not some race-condition number

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Other synchronization primitives:

  • asyncio.Event — signal between coroutines
  • asyncio.Condition — wait for a condition to be true
  • asyncio.Semaphore — limit concurrent access

Running Blocking Code in asyncio

Sometimes you need to call a blocking function (CPU-intensive or a non-async library) without blocking the event loop:

import asyncio
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor

# For blocking I/O (database drivers without async support, etc.)
async def read_file_async(path: str) -> str:
    loop = asyncio.get_event_loop()
    with ThreadPoolExecutor() as pool:
        content = await loop.run_in_executor(pool, open(path).read)
    return content

# For CPU-heavy work (data processing, image resizing, etc.)
def cpu_intensive_task(data: list) -> int:
    return sum(x ** 2 for x in data)

async def main():
    loop = asyncio.get_event_loop()
    data = list(range(1_000_000))

    with ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, cpu_intensive_task, data)
    print(result)

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

Async Context Managers and Iterators

import asyncio

# Async context manager
class AsyncDatabase:
    async def __aenter__(self):
        print("Connecting to DB...")
        await asyncio.sleep(0.1)
        return self

    async def __aexit__(self, *args):
        print("Closing DB connection")
        await asyncio.sleep(0.05)

    async def fetch(self, query: str):
        await asyncio.sleep(0.1)
        return [{"id": 1}, {"id": 2}]

# Async generator (async iterator)
async def paginate(db, query: str, page_size: int = 10):
    page = 0
    while True:
        results = await db.fetch(f"{query} LIMIT {page_size} OFFSET {page * page_size}")
        if not results:
            break
        for row in results:
            yield row
        page += 1

async def main():
    async with AsyncDatabase() as db:
        async for row in paginate(db, "SELECT * FROM users"):
            print(row)

asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode


Common Mistakes

❌ Calling a coroutine without awaiting it

async def main():
    fetch_data()  # Does nothing! Returns a coroutine object silently.
    await fetch_data()  # Correct

Enter fullscreen mode Exit fullscreen mode

❌ Using time.sleep() instead of asyncio.sleep()

import time

async def bad():
    time.sleep(2)  # ❌ Blocks the ENTIRE event loop for 2 seconds

async def good():
    await asyncio.sleep(2)  # ✅ Yields control — other coroutines run

Enter fullscreen mode Exit fullscreen mode

❌ Forgetting asyncio.run() or running in wrong context

# ❌ This does nothing at the top level
async def main():
    ...

main()  # Just creates a coroutine object

# ✅ Correct
asyncio.run(main())

Enter fullscreen mode Exit fullscreen mode

❌ CPU-bound work on the event loop

async def bad():
    result = sum(x**2 for x in range(10_000_000))  # ❌ Blocks event loop
    return result

async def good():
    loop = asyncio.get_event_loop()
    with ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, lambda: sum(x**2 for x in range(10_000_000)))
    return result

Enter fullscreen mode Exit fullscreen mode

When to Use asyncio (and When Not To)

Use asyncio when:

  • Making many concurrent network requests
  • Building web servers or APIs (FastAPI, Starlette, aiohttp)
  • Working with WebSockets or streaming data
  • I/O-heavy scripts (database queries, file operations, API calls)

Don't use asyncio when:

  • Your code is CPU-bound — use multiprocessing instead
  • Your entire stack uses synchronous libraries that don't support async
  • The script is simple and sequential — it just adds boilerplate

Wrapping Up

asyncio is not about running things faster on a single CPU — it's about keeping your program productive while waiting for I/O. The mental model is simple: one thread, cooperative switching at every await.

Master gather(), create_task(), Semaphore, and Queue, and you'll have the tools to handle virtually any concurrent I/O workload Python throws at you.