Skip to content

Lock the GC root set while marking and visiting roots - #1438

Merged
Aidan63 merged 1 commit into
masterfrom
gc-root-lock
Oct 29, 2026
Merged

Aidan63 merged 1 commit into
masterfrom
gc-root-lock

Conversation

@Simn

@Simn Simn commented Oct 29, 2026

Copy link
Copy Markdown
Member

GCAddRoot, GCRemoveRoot and the offset root functions (GcAddOffsetRoot, GcSetOffsetRoot, GcRemoveOffsetRoot) take sGCRootLock. The collector iterated sgRootSet and sgOffsetRootSet without it, both in MarkAll and when visiting roots.

Stopping the world doesn't make that safe. Threads in a GC free zone, and threads that aren't registered at all, keep running during a collection and can still add and remove roots. If one does that while the collector is iterating, the iterator can be invalidated, or roots can be skipped and objects they reference collected. This came up in hxcpp_luv_io, where uv_close callbacks remove roots from a loop thread that is in a GC free zone (Aidan63/hxcpp_luv_io#1).

This PR takes the lock around both iterations. Holding it can't deadlock. Threads that hold it only do std::unordered_set / std::unordered_map operations, which never reach a GC safepoint, and the collector doesn't add or remove roots while it holds the lock.

Tested with hxcoro's cpp test suite on Windows, with the default and threadpool dispatchers.

🤖 Generated with Claude Code

GCAddRoot, GCRemoveRoot and the offset root functions take sGCRootLock,
but the collector iterated sgRootSet and sgOffsetRootSet without it.
Stopping the world doesn't protect these sets, because threads in GC
free zones and unregistered threads can still add and remove roots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Aidan63
Aidan63 merged commit 2379472 into master Oct 29, 2026
290 checks passed
@Simn
Simn deleted the gc-root-lock branch October 30, 2026 10:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants