Python: Why 8 Threads Weren't Faster Than 1

Outline

Transcript

0:00 Imagine a data team with a slow cleanup step, pure Python, about a second per batch. Someone splits it across eight threads on a laptop with 10 fast cores, runs it again, and it still takes a second. My bet is the GIL. That's what I'd say in a code review, and then I'd move on. And that's half an answer; people assume naming the lock explains it. In the run we'll trace, one thread took 0.96 seconds and eight threads took 0.95. A thread that should wake every millisecond kept showing up about 20 milliseconds late. And a different build of the exact same Python release did the eight-thread run in 0.22. Wait. Same version?

0:41 Same version, 3.14.8, same laptop. Everything here comes from CPython's source code, the official docs, the Python enhancement proposals behind that second build, and a small benchmark I actually ran. Source links are in the description. Okay. So just naming the GIL doesn't explain the late sleeper, or the 0.22. Let's hear it. First, the setup. One small job: 40 million rounds of plain Python arithmetic, split evenly across one, two, four or eight threads. With the standard build, all four land at about 0.95 seconds.

1:15 The threads run, then. They just don't add up. Yep. Then I added a small ticker thread. It sleeps 1 millisecond, wakes, notes how late it was, and repeats for 2 seconds. Alone, it woke about thirteen hundred times, usually about 0.5 milliseconds late. And next to busy threads? With four threads crunching numbers, about 70 times. Half of those wakeups came at least 21 milliseconds late. Oh, wow. Thirteen hundred wakeups down to 70. So that 1-millisecond nap really does cost 20. That's a latency problem for anything in that process with a timer, a heartbeat or a metrics flush.

1:55 Yeah, and that's with only four threads busy. Then the 3rd measurement: eight threads that each sleep half a second. If the lock covered sleeping too, that'd be 4 seconds. They finished together, in 0.51 seconds. Huh. So sleeping threads overlap, computing threads take turns, and the ticker is stuck in between. Three puzzles. And I'd still bet on one lock behind all of them. Go on, let's cash in your bet. It's the GIL. The threading docs say it plainly: in CPython, only one thread can execute Python code at once.

2:28 On the standard build, anyway. A thread has to hold the global interpreter lock to run any. I'll admit, I knew that sentence for years and still kind of pictured threads sharing the cores, just bumping into each other a bit. A lot of us carry that picture. Your flat 0.95 is what strict turn-taking looks like: no Python ran in parallel. Which doesn't explain your late ticker yet. So the ticker's problem has to be the handoff. How does a waiting thread ever pry the lock loose from a busy one? It asks. After 5 milliseconds without it, the default switch interval, the waiter sets a drop request.

3:06 The busy thread notices the next time it loops back or calls a function, lets go, and then waits until another thread has actually taken over. Huh, it waits to see someone else take it. So it's one microphone. When your 5 milliseconds of waiting run out, you wave, the speaker finishes the sentence and lets go. Does whoever waved first get it next? Nope, no sign-up sheet. The sys docs say the operating system picks who. Take a ticker like yours: it wakes up next to four busy threads, and every one without the microphone is waving too, so it can lose several rounds in a row.

3:42 That typical delay of 21 is, About four turns of 5 milliseconds each; that's our reading of the code plus your numbers, not a documented figure. Which puts the ticker in the back row with its hand up. And the sleeping threads skip all that? Poor thing. Mostly, yes. Blocking calls like time dot sleep, or a socket read, for example, let go of the lock while they wait and only ask for it back to continue. That's why eight half-second sleeps overlap. The lock guards running Python code, not waiting.

4:16 Great for a web scraper, and useless for a pure-Python number cruncher. Now, useless on this build, sure. But in 3.14, a second build became officially supported. The free-threaded build, usually installed as python 3.14 t, runs with the global lock switched off. Instead it makes reference counting thread-safe and puts small locks on individual objects, so threads run Python side by side instead of taking turns. Right, the build behind my 0.22. And all that bookkeeping must cost something on one thread.

4:51 It does. PEP 703, the proposal behind this build, says most of that cost comes from the thread-safe reference counting, then the per-object locks. What did your run show? About 2%, 18 milliseconds on a 1-second job. The free-threading guide quotes an average of about 1% on Apple silicon Macs and about eight on x86 Linux. And with more threads? On paper, eight should get close to eight times. Two threads, 0.49 seconds. Four, 0.31. Eight, 0.22, about four and a half times faster than one thread. And the ticker woke half a millisecond late at the median, down from 21.

5:32 So the ticker was never bad at sleeping. It was stuck waving for the microphone. But eight threads, and less than five times faster? That bugged me too. In a follow-up, eight separate processes on the standard build each kept their full speed, so the cores were there. Threads sharing one free-threaded process each ran slower than they did alone. I ruled out threads fighting over one shared object, and the cost of allocating new objects, and honestly, I haven't found the cause yet. Even so, that's a big speedup.

6:03 Why isn't it the default? Because PEP 779 only made it supported, for one; making it the default is a later decision. But in practice, a lot of it comes down to extensions. A compiled module has to declare that it's safe without the lock. Import one that hasn't, and CPython prints a warning and turns the lock back on for the whole process, until it exits. That part I'd read, and I didn't quite believe it, so I tested it. Suppose a date-parsing library three levels down ships a C extension nobody updated.

6:35 I wrote a tiny one that declares nothing. Before the import, sys dot underscore is GIL enabled said false; right after, true. Eight threads went straight back to 0.96, and the ticker was late again. Oh, man. That deep in the dependency tree, no one on the team even chose it. And in most production services I've seen, a startup warning like that lands in a log nobody reads. Exactly. Run your tests on the free-threaded build with that warning turned into an error. The first extension that would re-enable the lock fails its import and names itself.

7:11 Fix or swap it, rerun, and repeat until the suite imports clean. Dash X GIL equals zero can force the lock off, at your own risk, since that extension never promised it was safe. Yeah, and that only covers imports your tests actually trigger. Being free-threaded isn't a property of the binary. It's a fact about the process, after every import. I love that. So what do I actually do with eight slow threads? Start with what they're waiting on. If it's I/O, like network calls or sleeps, threads overlap on either build.

7:45 Hold on. My ticker was just sleeping too, and it still came back late. Fair. Waiting is free; getting the lock again isn't. Your ticker wakes up, somebody else has the microphone, and it has to wave like everyone else. On the standard build, keep CPU-heavy threads out of any process that has to answer on time. And the CPU work itself? Processes. Swap the thread pool executor for a process pool executor; same interface, and every worker gets its own interpreter and its own lock, but only picklable data crosses between them, and that copying costs time.

8:19 For a pure loop like mine, processes still won. In that same follow-up eight processes took 0.15 seconds; eight free-threaded threads took about 0.2. Partly because almost nothing had to be pickled. Real data changes that, and then the other way out is native code that drops the lock, like hashlib does for inputs over about 2 kilobytes, for example. Right. But some teams can't take any of those exits. One of the reports in PEP 703 came from an AI lab. Of course it did. An engineer on DeepMind's reinforcement learning team said they often saw the lock become the bottleneck with fewer than 10 threads, and in many cases found the inter-process communication too big an overhead.

9:03 That's a team that wants 50 to 100 threads per process, though. Take a nightly batch job: processes are usually fine there. For workloads like theirs, the free-threaded build matters. With conditions. Like checking that the lock is still off? Once your startup imports finish, and again in your health check, since a later lazy import can flip it. And you still lock your own shared state. Yeah, the build turns off the GIL, not your race conditions. Personally, I'd make the GIL check fail the rollout. Agreed.

9:35 Otherwise you'd blame your own code long before anyone finds that one warning in the logs. Now, back to the team from the start: eight threads, still 1 second. Their threads were all waiting on one lock. Check which build you run, confirm the lock stays off after your imports, and pick threads, processes or native code by what the work waits on. Three checks, for a symptom I'd have waved through in code review. If threads didn't make it faster... ...they were taking turns. Thanks for listening to Learning Podcasts.