为什么使用线程局部存储(TlsAlloc、TlsGetValue、ets)而不是局部变量
我的问题是为什么在线程函数中使用 TLS 机制而不仅仅是局部变量?您能否提供一些很好的例子,或者 TLS 相对于本地变量有什么优势? 谢谢你, 马特乌什
my question is why use TLS mechanism instead of just local variables in a thread function? Can you please provide some fine example, or what's the advantage of TLS over local vars?
Thank you,
Mateusz
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您可以使用局部变量,那么就这样做,并且您总是可以使用局部变量。只有作为最后的手段才应该使用线程本地存储,它具有与全局变量几乎相同的缺点。尽管您正在寻找使用线程本地存储的理由,但实际上最佳实践是寻找避免它的方法!
If you can use local variables then do so and you invariably can use locals. Only as a last resort should you use thread local storage which suffers from almost all the same disadvantages as global variables. Although you are looking for a reason to use thread local storage, in fact best practice is to search for ways to avoid it!
以下是英特尔关于使用线程本地存储来减少同步的良好链接:
https://software.intel.com /en-us/articles/use-thread-local-storage-to-reduce-synchronization
Here is good link from Intel on using Thread-local Storage to Reduce Synchronization :
https://software.intel.com/en-us/articles/use-thread-local-storage-to-reduce-synchronization
TLS 对于诸如特定于线程的用户会话上下文信息之类的事情很有帮助,但可能会在各种不相关的方法中使用。在这种情况下,TLS 比在调用堆栈中上下传递信息更方便。
TLS is helpful for things like user session context information which is thread specific, but might be used in various unrelated methods. In such situations, TLS is more convenient than passing the information up and down the call stack.
我知道一个使用 TLS 的很好的例子。当您实现 LIBC 或将 LIBC 变体之一移植到新平台时,您需要某种“errno”变量(在单线程平台上只是 extern int errno)对于每个线程都是唯一的。 LIBC 函数只是将其存储在当前线程的 TLS 中,并且对 errno 的调用只是从 TLS 中读取它。 TLS 是使任何库线程安全的方法。您可以在 TLS 中存储任何类型的“静态”或“全局”数据,因此从另一个线程调用的同一函数不会破坏另一个线程中的“静态”或“全局”变量。这使得你的函数可以从不同的线程重入。
I know one very good example of using TLS. When you are implementing LIBC or porting one of the LIBC variants to new platform you need somehow 'errno' variable (which on single threaded platfrom is just extern int errno) to be unique for each thread. LIBC functions simply stores it in TLS of the current thread and a call to errno just reads it from TLS. TLS is the way to make any library thread safe. You store any kind on 'static' or 'global' data in TLS so the same function being called from another thread will not corrupt your 'static' or 'global' variables in another thread. Which makes you functions re entrant from different threads.
线程本地存储可用于在每个线程的基础上模拟全局或静态变量。 “普通”局部变量不能。
Thread-local storage can be used to emulate global or static variables on a per-thread basis. "Normal" local variables can't.