对Tls了解的兄弟进来看看
When a thread is created, an array of TLS_MINIMUM_AVAILABLE PVOID values is allocated, initialized to 0, and associated with the thread by the system. As Figure 21-1 shows, each thread gets its own array and each PVOID in the array can store any value.
当一个线程被创建出来,系统将会关联与该线程一个存放PVOID值的数组,每个线程都会有这样一个数组.
Before you can store information in a thread's PVOID array, you must know which index in the array is
available for use—this is what the earlier call to TlsAlloc is for. Conceptually, TlsAlloc reserves an index for you. If TlsAlloc returns index 3, it is effectively saying that index 3 is reserved for you in every thread currently executing in the process as well as in any threads that might be created in the future.
在我们往PVOID数组存放数据之前,我们必须首先调用TlsAlloc取得一个可用的PVOID数组成员的Index .如果TlsAlloc返回的Index是3,那么当前进程的所有线程的PVOID数组的 Index为3的成员都被保留(是否是:只要一个线程被分配了Index=3,那么其他线程的Index 3也就不能使用了,尽管各个线程的PVOID数组是不同的,如果是这样,那为什么要这么做呢?)
上面这两段是Windows核心编程里说的,不知道我理解对不对?
我创建了一个MFC工程进行了验证,用一个Button响应函数在主线程中 多次调用TlsAlloc,每次获得的索引号都不一样,是
依次递增的,这个还能解释,相当于每次都获得数组里一个新的空位来保存数据. 但是我创建了几个线程,在线程里面调用
TlsAlloc,我发现得到的Index是跟着主线程得到的Index递增的,即:主线程最后一次调用TlsAlloc得到的index是10的话,
那么新开的线程得到的一定是11, 这跟书上讲的不一样.经过这样的试验,我觉得是每个进程的所有线程共享一个 存放PVOID值的数组, 但感觉这样跟线程本地存储的概念不相符和,而且跟书上讲的也不一样.
以前一直没有仔细研究过TLS,现在很想把Tls弄明白了,还请知道的高手帮忙解答下^_^