5 ms·
Arc is there if you need to send that singleton between threads. If your program is a single-thread non-async one, you can drop both Arc and Mutex, leaving you
by Fiahil 6y ago
Arc is there if you need to send that singleton between threads. If your program is a single-thread non-async one, you can drop both Arc and Mutex, leaving you with just a regular data field :)
- steveklabnik 6y agoIf 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.)
- bluejekyll 6y agoTLS 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.
- steveklabnik 6y agoAbsolutely, 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.
- bluejekyll 6y agoYes. Absolutely. TLS is definitely the preferred pattern in this case.
- cesarb 6y agoTLS 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.)
- pandalicious 6y agoFor anyone else that’s confused, TLS = thread local storage
- steveklabnik 6y agoYes, sorry, I figured that in this thread (eyyyyyy) it would be unambiguous, but probably should have elaborated anyway. Thanks.
- deleted 6y ago[deleted]
- eximius 6y agoArc is still only necessary if your T has interior mutability or some other reason to not be Sync.
- jupp0r 6y agoOP mentioned that T is mutable