Skip to content
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

Are long-lived references to thread_local variables allowed? #541

Open
theemathas opened this issue Oct 27, 2024 · 4 comments
Open

Are long-lived references to thread_local variables allowed? #541

theemathas opened this issue Oct 27, 2024 · 4 comments

Comments

@theemathas
Copy link

Is the following code sound?

thread_local! {
    static X: String = String::from("abc");
}

/// SAFETY: If this function is called in a certain thread,
/// then the returned reference must not be used after
/// the "top-level function" of that thread finishes.
unsafe fn smuggle() -> &'static String {
    &*X.with(|a| a as *const String)
}

In other words, is it guaranteed that:

  • A thread-local's address is stable?
  • &mut references won't be created to thread-locals until it's time to run thread-local destructors?
@RalfJung
Copy link
Member

There is no way to get a &mut to thread-locals in safe code. And the address is indeed stable.

However once the destructor of the thread-local gets run, the reference gets invalidated, so the 'static lifetime is a lie. You seem to be aware of that.

The notion of "soundness" of an unsafe function is non-trivial to define so it's not entirely clear what you are asking about.

@theemathas
Copy link
Author

And the address is indeed stable.

Is this documented anywhere?

@RalfJung
Copy link
Member

Not that I am aware of.

thread-locals are a library feature, so this would be a t-libs-api issue to be raised in https://github.com/rust-lang/rust/issues/

@joboet
Copy link
Member

joboet commented Nov 18, 2024

The answers to your questions are currently yes and yes. Als Ralf pointed out, this isn't documented anywhere though, so it isn't something you should rely on (yet). On the other hand, I don't consider this behaviour likely to change. Thus, if you truly need this, please file a PR adjusting the thread_local! documentation to add the necessary guarantees, and T-libs-api might consider adding them.

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

No branches or pull requests

3 participants