线程本地存储/Windows [英] Thread local storage / Windows

查看:71
本文介绍了线程本地存储/Windows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出本机代码(C/C ++),有人可以解释线程本地存储吗?仅仅是一个让线程控制自己变量的生存期的技巧,还是编译器或硬件执行了一些隔离/保护措施?

Given native code (C/C++), could someone explain thread local storage? Is it simply a trick that allows threads to control the lifetime of their own variables, or is there some isolation/protection enforcement by either the compiler or the hardware?

基础平台重要吗?

此外,相对于上述情况,普通TLS和光纤安全" TLS有什么区别?

Further more, what is the difference between plain TLS and "Fiber-safe" TLS, with respect to the above?

对不起,我用谷歌搜索,但我能找到的只是如何使用TLS(我已经知道),而不是幕后的怪异细节.

Sorry, I googled, but all I could find was how to use TLS (which I already know) but not the geeky details behind the scenes.

推荐答案

线程本地存储(TLS)由操作系统管理.内核中的每个线程对象都包含一个本地的TLS插槽数组.在运行时,应用程序的代码可以为需要的每个TLS变量(例如,声明为__thread__declspec(thread)的变量,具体取决于编译器)调用TlsAlloc(),以将可用索引保留到TLS数组中.然后,每个线程可以使用TlsGetValue()TlsSetValue()来读取/写入存储在调用线程的TLS数组中这些索引处的值.使用TLS完成后,应用程序可以调用TlsFree()释放其保留的索引.

Thread-local Storage (TLS) is managed by the OS. Every thread object in the kernel contains a local array of TLS slots. At runtime, the app's code can call TlsAlloc() for each TLS variable it needs (such as for variables declared as __thread or __declspec(thread), depending on compiler) to reserve available indexes into the TLS array. Each thread can then use TlsGetValue() and TlsSetValue() to read/write values that are stored in the calling thread's TLS array at those indexes. When done using TLS, the app can call TlsFree() to release its reserved indexes.

例如,在应用启动时,应用调用一次TlsAlloc()来保留TLS索引0.在随后运行的每个线程中,任何给定的线程都可以为TLS索引0调用TlsSetValue(),并且该值将存储在本地对于该特定线程,因此存储在其他线程的TLS索引0处的值将不会受到影响.

For example, at app startup, the app calls TlsAlloc() once to reserve TLS index 0. Inside each thread that subsequently runs, any given thread can call TlsSetValue() for TLS index 0, and that value will be stored locally for that specific thread, thus values stored at TLS index 0 for other threads will not be affected.

有关更多详细信息,请参考MSDN:

Refer to MSDN for more details:

线程本地存储

纤维在线程内部运行.因此,在同一线程中运行的多个光纤将为该线程共享相同的TLS阵列.如果一根光纤在TLS索引0处设置值,则在同一线程中运行的所有光纤都会受到影响. Fiber-Safe TLS只是一种编译器优化,可以防止光纤在其生命周期内从一个线程跳到另一个线程时缓存任何TLS信息.

Fibers run inside of threads. So multiple fibers running in the same thread will share the same TLS array for that thread. If one fiber sets a value at TLS index 0, all fibers running in that same thread are affected. Fiber-Safe TLS is just a compiler optimization that prevents a fiber from caching any TLS information, in case that fiber jumps from one thread to another during its lifetime.

这篇关于线程本地存储/Windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆