Preferences

If you really need something that's only for a single thread, then using TLS is gonna be better than a static.

(I actually want to write a blog post about this... haven't done so yet though. People reach for static too often and thread_local! too little, IMHO. Of course, not needing either is best.)


TLS has many of the same downsides of most global state. It does remove the concurrent access issues (as long as it is only used inside a single thread), but it still creates a testing problem if access to it is not restricted. That is, don’t make globals publicly accessible, just like you wouldn’t make all data in an object publicly accessible.
Absolutely, I'm not saying that people should be reaching for global state more, I'm saying that if you really need global state, reaching for TLS over a static is often the right call, because you're minimizing the global-ness, which drops some of the type system restrictions.

That is, too many people skip straight to static without even considering TLS, not that they should be using TLS more often in general.

Yes. Absolutely. TLS is definitely the preferred pattern in this case.
TLS has the additional downside that it makes it harder to move part of the processing to another thread, because the other thread will have a different TLS state. That is, once you have TLS, x() and thread::spawn(x).join() might no longer do the same thing. Using TLS creates thread affinity when one might not be expecting it.

(I've seen way too many times a thread-local being used as a way to smuggle extra parameters, often through several layers; inevitably, this breaks when one of the intermediate layers decides to run things in a separate thread pool.)

For anyone else that’s confused, TLS = thread local storage
Yes, sorry, I figured that in this thread (eyyyyyy) it would be unambiguous, but probably should have elaborated anyway. Thanks.

This item has no comments currently.

Keyboard Shortcuts

Story Lists

j
Next story
k
Previous story
Shift+j
Last story
Shift+k
First story
o Enter
Go to story URL
c
Go to comments
u
Go to author

Navigation

Shift+t
Go to top stories
Shift+n
Go to new stories
Shift+b
Go to best stories
Shift+a
Go to Ask HN
Shift+s
Go to Show HN

Miscellaneous

?
Show this modal