Repository navigation
Thread.new: let finished threads be collected (DLR ThreadLocal, Thread.list registry) - #208
Conversation
Thread.new { }.join cost ~51-64 us main-thread CPU and ~150-190 us process
CPU (CRuby 4.0.9: 27-33 / 51-59 us on the same loaded box). A perf profile
of 100k threads put 35-62 % of the process's samples on the finalizer
thread in the CLR's ThreadStore::RemoveThread, plus GetThreadList during
GC suspensions. A heap dump taken mid-loop showed why: ~4,700 dead threads
in the CLR's thread list (a plain C# create/join loop has ~500), their
Thread objects unreachable but promoted to gen 2. They had been held by the
DLR's ThreadLocal<InterpretedFrame> (InterpretedFrame.CurrentFrame), whose
entries held their owning Thread and outlive the thread until the array
next grows. The CLR keeps a dead thread's native record and its
ManagedThreadId until the Thread is finalized, so ids were not reused,
the array kept growing by one (a copy per new id) and the list the
finalizer walks for each removal stayed thousands long. 20 joined Ruby
threads were all still alive after three full collections.
Patch 0108 gives each entry a per-thread token object instead of the
Thread (a ConditionalWeakTable maps a Thread to its token, weakly, for
TryGetValue from patch 0001). A finished thread is collected, its id is
reused, and a new thread with that id replaces the stale entry on first
use.
Measured 2026-11-11, Release, `taskset -c 3`, warm-up then best of 5 x
20k threads, three interleaved rounds on a box at load 13-21 (before ->
after; CRuby 4.0.9 27-33 / 51-59 us):
- net10.0: 51-60 / 152-176 -> 49-55 / 142-164 us (thread / process CPU)
- net11.0: 48-55 / 159-173 -> 41-47 / 124-136 us
- finalizer-thread CPU for 50k threads (net11.0): 0.38-1.21 -> 0.14-0.17 s
- allocation per thread: 6.3-7.7 KB -> 3.1-3.6 KB (the array copies)
- dead threads in the CLR's list mid-loop: ~4,700 -> ~200
- joined threads alive after full GCs: 20 of 20 -> 0
What is left is creating and destroying the CLR thread itself: a C# loop
of new Thread(...).Start(); Join() costs 39-52 / 112-145 us here.
Tests: Thread_FinishedThreadCollected1 (fails on master with 20),
Dlr_ThreadLocalOwner1 (a finished thread is collected; new threads, the
one reusing its id included, start without its value; TryGetValue reads
another live thread's value).
Part of #89.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
RubyThreadInfo._registered, the list Thread.list enumerates, kept a finished thread's info until the next prune: up to 64 thread creations later, or twice as many as were registered at the last prune. Until then the finished Thread was reachable, so the GCs in between promoted it, and it stayed, with the CLR's record of the dead thread, until a gen-2 collection. With DLR patch 0108 alone, the 20 joined threads of Thread_FinishedThreadCollected1 were still all alive after full collections; RubyThreadStart now removes its info as its last step (searching from the end, where a thread that finishes usually is). Thread.list already left out threads that are not alive, so what it reports does not change. Also fixes Dlr_ThreadLocalOwner1, which read ThreadLocal.Value (which gives the thread an entry) before asking TryGetValue whether it had one. Part of #89. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Next included review available in 22 minutes. View limit details
|
| // Whichever ids they get - the finished thread's among them, once the CLR hands it out again - new | ||
| // threads start with nothing, and their values are their own. | ||
| for (int i = 0; i < 20; i++) { |
There was a problem hiding this comment.
Dlr_ThreadLocalOwner1 can pass without exercising a reused ManagedThreadId. The loop creates 20 threads but never checks whether one gets the finished thread's ID. If every thread gets a fresh slot, both freshness checks pass even if the owner check is broken.
Return the original ID from the helper, collect between bounded batches, and assert that reuse occurred before counting this case as covered.
Prompt To Fix With AI
This is a comment left during a code review.
Path: Src/IronRuby.Tests/Runtime/MiscTests.cs
Line: 2546-2548
Comment:
**Reused slots may go untested**
`Dlr_ThreadLocalOwner1` can pass without exercising a reused `ManagedThreadId`. The loop creates 20 threads but never checks whether one gets the finished thread's ID. If every thread gets a fresh slot, both freshness checks pass even if the owner check is broken.
Return the original ID from the helper, collect between bounded batches, and assert that reuse occurred before counting this case as covered.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Part of #89 (the
Thread.new.joinitem).What was wrong
A perf profile of a
Thread.new { }.joinloop put most of the process CPU on the finalizer thread, in the CLR'sThreadStore::RemoveThread. A heap dump taken during the loop showed why. The CLR's thread list held about 4,700 dead threads; a plain C# create/join loop holds about 500. TheirThreadobjects were unreachable, but they had been promoted to gen 2. Two things had kept them alive:ThreadLocal<T>(InterpretedFrame.CurrentFrame). Each entry held its owningThread, and an entry outlives its thread until the array next grows. The CLR keeps a dead thread's native record and itsManagedThreadIduntil theThreadis finalized. So ids were not reused, the array grew by one element per new id (copying itself each time), and the list the finalizer walks for each removal stayed thousands of entries long.RubyThreadInfo._registered(the list behindThread.list). It kept a finished thread until the next prune, which comes up to 64 thread creations later, or later still when many threads are alive. That was enough for the thread to be promoted.The new test checks this directly: 20 joined threads were all still alive after three full collections on master (on net10.0 and net11.0); with this branch none are.
Changes
0108-ThreadLocal-no-dead-thread-roots.patch: an entry carries a per-thread token object instead of theThread. AConditionalWeakTablemaps aThreadto its token, weakly, forTryGetValue(patch 0001, used byThread#backtrace). A finished thread is then collected and its id reused, and a new thread with that id replaces the stale entry the first time it uses the slot. The patch is documented inBuild/dlr-patches/README.md. All patches apply in order toDLR_REF.ThreadOps.RubyThreadStart: as its last step it removes the thread's info from_registered(searching from the end of the list).Thread.listalready left out threads that are not alive.Thread_FinishedThreadCollected1prints 20 on master and 0 here.Dlr_ThreadLocalOwner1: a finished thread is collected; new threads start without its value, including one that gets its id when the CLR reuses it;TryGetValuereads another live thread's value.This change does not touch
ThreadOps.Fiber.csorRubyUtils.cs.Numbers
Measured 2026-11-11, Release,
taskset -c 3. Each figure is the best of 5 × 20k threads after a warm-up, over three interleaved rounds. The box was at load 13–21, so the ranges are wide.What is left is the cost of creating and destroying the CLR thread itself. A C# loop of
new Thread(...).Start(); Join()costs 39–52 µs main-thread CPU and 112–145 µs process CPU on the same box.UnsafeStartmakes no measurable difference. 75 % of the bytes that are still allocated per thread are the runtime's own thread-static array (GetGCThreadStaticsByIndexSlow).Pooling CLR threads: evaluated, not done
A pool of parked workers would cost about 8–15 µs per hand-off, plus about 2.5 µs for a distinct identity object. Pooling is not safe in IronRuby today, because a Ruby
Threadis itsSystem.Threading.Thread:Thread.currentmust be a new object for eachThread.new, but a pooled worker'sThread.CurrentThreadis the worker.Thread.CurrentThreadsites and every CLR call on a Ruby thread object (Join,IsAlive,ThreadState,Interrupt,Name,Priority,ManagedThreadId).RubyUtilsand the fiber ownership inThreadOps.Fiber.cs.That is a redesign of the threading identity, and it would conflict with the concurrent
Thread#raise/fiber work.Checked
Queue#initializeinto/towording error.Timeout.timeout raises specified error type when it times outfails now and then; master fails it alone too (1 run in 3 on master, 2 in 3 on the branch).reviewskill, run by a separate agent, reported no defects.Local DLR checkouts need
0108applied (git -C ../dlr apply Build/dlr-patches/0108-*.patch); otherwisecheck-dlr-patches.shfails the build.🤖 Generated with Claude Code
The PR appears safe to merge, with a non-blocking gap in the ID-reuse test.
Fix with agent prompt
Summary
Lets finished Ruby threads be collected sooner:
The new ownership test should also check that it actually exercised a reused ID.
Diagram
%%{init: {'theme': 'neutral'}}%% flowchart LR A[Thread runs Ruby code] --> B[DLR slot stores owner token] C[Weak table maps Thread to token] --> B A --> D[Ruby block finishes] D --> E[Remove info from registered list] E --> F[Thread can be collected] F --> G[ID can be reused] G --> H[New owner token replaces stale slot]Reviews (1) · Last reviewed commit: "Thread: drop a finished thread from the ..." · Reviewed by Greptile