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

推荐订阅源

B
Blog RSS Feed
C
CERT Recently Published Vulnerability Notes
P
Proofpoint News Feed
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
H
Help Net Security
Recorded Future
Recorded Future
The Register - Security
The Register - Security
F
Full Disclosure
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hackread – Cybersecurity News, Data Breaches, AI and More
爱范儿
爱范儿
Security Archives - TechRepublic
Security Archives - TechRepublic
Simon Willison's Weblog
Simon Willison's Weblog
Cisco Talos Blog
Cisco Talos Blog
I
InfoQ
T
Tenable Blog
T
Tor Project blog
人人都是产品经理
人人都是产品经理
D
DataBreaches.Net
NISL@THU
NISL@THU
Google DeepMind News
Google DeepMind News
博客园 - 叶小钗
B
Blog
V
V2EX
Jina AI
Jina AI
L
LangChain Blog
月光博客
月光博客
W
WeLiveSecurity
U
Unit 42
AWS News Blog
AWS News Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 聂微东
V
Visual Studio Blog
A
Arctic Wolf
T
Tailwind CSS Blog
The Cloudflare Blog
SecWiki News
SecWiki News
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
S
Securelist
www.infosecurity-magazine.com
www.infosecurity-magazine.com
腾讯CDC
雷峰网
雷峰网

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
How Python's GIL actually works (and when it bites you)
Athreya aka · 2026-05-10 · via DEV Community

Hello, I'm Maneshwar. I'm building git-lrc, a Micro AI code reviewer that runs on every commit. It is free and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

I remember the first time the GIL ruined my evening.

I was working on FreeDevTools and had a script that needed to parse, validate, and rewrite metadata for a few hundred thousand small markdown files and finally stores it into sqlite DB.

The bulk of my work was pure Python, a lot of looping, dictionary lookups, string concatenation, and small object churn. No NumPy, no Pillow, no native libraries doing the heavy lifting.

The single-threaded version was going to take forever, so I did what any reasonable person would do, I threw threads at it.

Eight worker threads. Should be a lot faster, right?

It was the same speed. Maybe a hair slower. I stared at the terminal for a solid minute thinking I'd done something wrong.

I had not done something wrong. I had met the GIL.

distracted boyfriend meme Girlfriend =

So what is it

GIL stands for Global Interpreter Lock.

The short version: it's a lock inside CPython (the standard Python you almost certainly use) that ensures only one thread executes Python bytecode at a time, within a single interpreter.

That word "bytecode" is doing a lot of work, and we'll come back to it.
For now, the simple version is: even if your laptop has 16 cores and you spin up 50 threads, only one of those threads is running Python code at any given instant. The rest are waiting their turn.

The threads do take turns.

CPython periodically gives other waiting threads a chance to acquire the GIL (the interval is 5 ms by default, tunable via sys.setswitchinterval()).

The actual handoff happens at the next safe point in the bytecode evaluation loop, so things look concurrent, even though no two threads are executing Python in parallel.

image 815

An analogy: you can hire ten cooks, but if there's only one knife, nine of them are watching the tenth one chop onions. They can rotate, but they can't chop simultaneously (Unless one of the cooks leaves the kitchen to wait for ingredients, which is roughly what happens during blocking I/O.)

One important caveat before we go further: the GIL is a CPython thing.
Other Python runtimes like Jython and IronPython don't use the same GIL model, and modern CPython now also ships an experimental free-threaded build.

When people say "Python has a GIL," they really mean "the most common Python implementation has a GIL."

Why does this exist

Not because anyone was lazy. The GIL is a real engineering tradeoff.

Python primarily manages memory with reference counting, plus a cyclic garbage collector for reference cycles.

Every variable assignment, every function call, every time you stuff something into a list, there's a counter being incremented or decremented in the background.

If two threads update those counters simultaneously without coordination, you get race conditions, and race conditions in memory management lead to crashes and corrupted data.

The alternatives to the GIL is fine-grained locking on every object, or rewriting the memory model that come with their own costs: more overhead per operation, slower single-threaded code, and a much harder life for anyone writing C extensions.

Much of the C extension ecosystem (NumPy, Pillow, lxml, every database driver) was built assuming the GIL exists. Rewriting all of that for thread safety is a generational project.

So the GIL stuck around because the tradeoff genuinely favored it: simpler implementation, faster single-threaded code, and an easy contract for C extensions.

The cost was no parallel execution of Python bytecode and for most users, that tradeoff was acceptable.

Let's actually see it

Here's a script that demonstrates the limitation. Two heavy countdowns, run sequentially, then again with threads:

import time
import threading

def countdown(n):
    while n > 0:
        n -= 1

COUNT = 50_000_000

start = time.time()
countdown(COUNT)
countdown(COUNT)
print(f"sequential: {time.time() - start:.2f}s")

start = time.time()
t1 = threading.Thread(target=countdown, args=(COUNT,))
t2 = threading.Thread(target=countdown, args=(COUNT,))
t1.start(); t2.start()
t1.join();  t2.join()
print(f"threaded:   {time.time() - start:.2f}s")

Enter fullscreen mode Exit fullscreen mode

The threaded version will be roughly the same speed, sometimes a hair slower because of GIL switching overhead

This benchmark is intentionally synthetic, a real workload has more nuance but it makes the core limitation visible in a way nothing else does.

The plot twist: threading isn't useless

Here's the part that took me embarrassingly long to internalize.

The GIL is released when Python is doing blocking I/O or, more precisely, when the C code implementing that I/O explicitly releases it.

Reading a file, waiting on a network request, querying a database, sleeping, the underlying C call releases the GIL during the wait, lets other threads run, then reacquires it on the way back.

Which means threading is genuinely useful, just not for what I initially thought.

import time
import threading

def fake_request():
    time.sleep(2)  # pretend this is a network call

start = time.time()
fake_request()
fake_request()
fake_request()
print(f"sequential: {time.time() - start:.2f}s")

start = time.time()
threads = [threading.Thread(target=fake_request) for _ in range(3)]
for t in threads: t.start()
for t in threads: t.join()
print(f"threaded:   {time.time() - start:.2f}s")

Enter fullscreen mode Exit fullscreen mode

image

The rule of thumb that finally clicked for me:

  • if your workload is mostly waiting on I/O, threads often help a lot
  • if your workload is mostly computing in pure Python bytecode, threads usually won't speed it up

Web scrapers, API clients, anything that talks to a database or the filesystem for this, threading (or asyncio) is great.

Tight pure-Python loops that crunch data, threads will let you down.

Quick aside on asyncio, since it keeps coming up: asyncio isn't an alternative to threading for using more cores.

It's concurrency in a single thread i.e one event loop juggling many I/O-bound coroutines without the overhead of OS threads.

It's excellent for high-concurrency I/O workloads, but it does not bypass the GIL for CPU-bound Python code.

If your workload is CPU-bound, asyncio won't probably save you either.

Drake meme. Rejecting:

When threads do use multiple cores

This is the section I wish someone had handed me a year ago.

The GIL only restricts execution of Python bytecode.

C extensions can release the GIL while they do their work in native code, and many of them do exactly that.

When the GIL is released inside a C extension, other Python threads can run in parallel on multiple cores.

This is why "threads can't use multiple cores in Python" is one of the most repeated half-truths on the internet.

Threads doing work inside a well-written C extension absolutely can.

If the underlying numerical or native library releases the GIL and isn't already saturating your CPU internally, threading on top can give you some parallelism. (If you want to go down the rabbit hole, this Stack Overflow thread has the canonical back-and-forth on the question)

This is also why scientific Python feels so much faster than the language has any right to be: most of the actual work is happening in C/C++/Fortran, and the GIL gets out of the way for the duration.

Okay but what if I genuinely need to crunch in pure Python

This is where multiprocessing comes in.

Each process gets its own Python interpreter, its own memory, its own GIL. Spin up four processes on a four-core machine, and you actually get four cores' worth of work — no lock fighting, no taking turns.

image

import time
from multiprocessing import Process

def countdown(n):
    while n > 0:
        n -= 1

if __name__ == "__main__":
    COUNT = 50_000_000
    start = time.time()
    p1 = Process(target=countdown, args=(COUNT,))
    p2 = Process(target=countdown, args=(COUNT,))
    p1.start(); p2.start()
    p1.join();  p2.join()
    print(f"multiprocessing: {time.time() - start:.2f}s")

Enter fullscreen mode Exit fullscreen mode

image

For sufficiently CPU-heavy workloads on multi-core systems, this is usually faster than the sequential version.. Won't always be exactly half, it depends on your CPU topology, thermal headroom, and what else your machine is doing but yeah, you'll see some parallelism.

The catch: processes are heavier than threads. They take longer to spin up, they don't share memory by default, and passing data between them involves serialization (usually pickling), which has its own gotchas. If you've ever seen a Can't pickle local object error, you've met one of them.

For most everyday cases, reach for concurrent.futures.ProcessPoolExecutor. It's a friendlier wrapper that makes multiprocessing feel almost as easy as threading.

The places it actually bites in real life

Times I've watched people (also me) get burned:

  • writing a "fast" data transformation in pure Python with threads, expecting linear scaling, getting none
  • threading a pandas pipeline that's mostly .apply() with a Python function. pandas drops into C and releases the GIL for vectorized ops, but .apply() calls back into Python — and Python is back to one thread at a time
  • web scrapers that thread the parsing with a pure-Python parser instead of the fetching. fetching is I/O (good for threads). HTML parsing can become CPU-bound, especially with html.parser. With lxml, you'd be fine because lxml releases the GIL, parser choice matters

The throughline is always the same: figure out whether your bottleneck is waiting, computing in pure Python, or computing in a C extension. Threading helps the first and third, not the middle.

Wait, isn't the GIL going away

Sort of.

PEP 703 the proposal to make the GIL optional in CPython — was accepted by the Steering Council in 2023, with explicit conditions: the rollout had to be gradual, ecosystem disruption had to stay manageable, and the entire effort could still be rolled back if it proved too disruptive.

Python 3.13 (October 2024) shipped the first experimental free-threaded build of CPython alongside the normal GIL-enabled build.
It allows running Python without the GIL, though many extension modules still rely on GIL assumptions and may re-enable it automatically when imported.

Python 3.14 substantially improved the experimental free-threaded runtime.
The adaptive interpreter was re-enabled, single-threaded performance penalties dropped substantially, and the project moved into Phase II of the Steering Council's rollout plan where free-threaded Python is considered supported, but still optional and not the default runtime.

CPython is clearly moving toward a future where no-GIL Python is viable but we're not at the point where the standard build is going away anytime soon.

Anakin/Padmé.

What to actually do with all this

If I had to compress everything I wish someone had told me earlier:

When your code is slow, before reaching for any concurrency, profile it. Find out where the time is going. Then ask one question: is this thread waiting, computing in pure Python, or computing inside a C extension?

  • waiting → threading or asyncio will help a lot
  • pure Python → threading won't help; reach for multiprocessing, or find a library that drops to C (NumPy, polars, anything with a native backend)
  • C extension that releases the GIL → threading already helps; you may not need anything else

And don't feel dumb if you've been bitten by this. Everyone has. The GIL is one of those things that's obvious in hindsight and completely opaque the first time you hit it.

Now you've hit it on purpose, in a controlled environment, with a blog post next to you. That puts you ahead of where I was.

Thats all folks

References

AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.*

Any feedback or contributors are welcome! It's online, source-available, and ready for anyone to use.

⭐ Star it on GitHub:


AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

See It In Action

See git-lrc catch serious security issues such as leaked credentials, expensive cloud operations, and sensitive material in log statements

git-lrc-intro-60s.mp4

Why

  • 🤖 AI agents silently break things. Code removed. Logic changed. Edge cases gone. You won't notice until production.
  • 🔍 Catch it before it ships. AI-powered inline comments show you exactly what changed and what looks wrong.
  • 🔁 Build a