-
Notifications
You must be signed in to change notification settings - Fork 12.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Avoid initialization checks when accessing thread locals #44025
Comments
We can just do what C(++) compilers do and support the lazy initialization in the compiler, by generating a wrapper function that would get called each time - not sure about reentrance implications but it should be doable. |
An alternative: have a dedicated I think having explicit separate constructs for compile-time initialization vs lazy initialization fits better with rust overall direction than "sufficiently smart compiler/stdlib optimizes lazy initialization away". If you care about We probably should have named the current macro |
This was implemented in #83416 as: thread_local! {
static FOO: u32 = const { 3 };
} |
The above syntax stabilized in 1.59, I'm going to go ahead and close this. |
Thread locals are often slower than they need to be. For example, if we have:
Every access of the form
FOO.with(|foo| ...)
will first check whetherFOO
is initialized, and then initialize it if this is the first access. On some (most?) platforms we can statically initialize thread locals with a constant expression (in this case the constant expression is777
).A check on every access can be fairly costly, and we should try to avoid checks whenever possible. It is possible to avoid them by using
#[thread_local]
instead ofthread_local!
, but that is an unstable feature without a clear stabilization plan...In #17954 @alexcrichton said:
@eddyb answered:
@arielb1 suggests:
@alexcrichton adds:
My question after all that would be:
Can we perhaps make the
thread_local!
macro expand to a special lang item that provides two implementations - one for the lazy initialization case and one for the static initialization zero-checks case? Then the compiler would choose one of them, depending on whether the initialization expression is a constant expression.The text was updated successfully, but these errors were encountered: