About Thread Local Variable Initialization

play1
play2

We can see from these two demos that, thread local variables can be initialized multiple times, and their temp initial values are observable.
My question is, is this a defined behavior? Maybe some of those happened

  • mutation to sth constant
  • access to sth uninitialized

I'm not familiar with thread local things. Please teach me if I think anything wrong.

thread_local is a way of defining a LocalKey, so LocalKey’s documentation is relevant. It includes:

A LocalKey ’s initializer cannot recursively depend on itself. Using a LocalKey in this way may cause panics, aborts or infinite recursion on the first call to with.

You’re getting the “infinite recursion” sort of behavior, but dodging it with additional state. But the documentation is telling you: don't rely on this doing anything in particular.

However, you can expect that it will not cause access to uninitialized memory or other undefined behavior, because LocalKey::with() is a safe function. If there was actually any way to cause UB with LocalKey, that would be a bug to report, not an expected outcome of misusing it.

1 Like