Skip to content

std: lazily allocate the main thread handle#132654

Merged
bors merged 4 commits intorust-lang:masterfrom
joboet:lazy_main
Jan 15, 2025
Merged

std: lazily allocate the main thread handle#132654
bors merged 4 commits intorust-lang:masterfrom
joboet:lazy_main

Conversation

@joboet
Copy link
Member

@joboet joboet commented Nov 5, 2024

#123550 eliminated the allocation of the main thread handle, but at the cost of greatly increased complexity. This PR proposes another approach: Instead of creating the main thread handle itself, the runtime simply remembers the thread ID of the main thread. The main thread handle is then only allocated when it is used, using the same lazy-initialization mechanism as for non-runtime use of thread::current, and the name method uses the thread ID to identify the main thread handle and return the correct name ("main") for it.

Thereby, we also allow accessing thread::current before main: as the runtime no longer tries to install its own handle, this will no longer trigger an abort. Rather, the name returned from name will only be "main" after the runtime initialization code has run, but I think that is acceptable.

This new approach also requires some changes to the signal handling code, as calling thread::current would now allocate when called on the main thread, which is not acceptable. I fixed this by adding a new function (with_current_name) that performs all the naming logic without allocation or without initializing the thread ID (which could allocate on some platforms).

Reverts #123550, CC @GnomedDev

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

O-unix Operating system: Unix-like O-windows Operating system: Windows S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-libs Relevant to the library team, which will review and decide on the PR/issue. T-rustdoc Relevant to the rustdoc team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

std::thread::Thread grew from one to two pointer sizes

9 participants