Thread Local StorageThreads may need to allocate and manage their own storage independently of and protected from other threads in the same process. One technique is to have the creating thread call CreateThread (or _beginthreadex) with lpvThreadParm pointing to a data structure that is unique for each thread. The thread can then allocate additional data structures and access them through lpvThreadParm. Program 7-1 used this technique. Windows also provides TLS, which gives each thread its own array of pointers. Figure 7-3 shows this TLS arrangement. Figure 7-3. Thread Local Storage within a Process
Initially, no TLS indexes (rows) are allocated, but new rows can be allocated and deallocated at any time, with a maximum of TLS_MINIMUM_AVAILABLE (at least 64) indexes for any process. The number of columns can change as new threads are created and old ones terminate The first issue is TLS index management. The primary thread is a logical place to do this, but any thread can manage thread indexes. TlsAlloc returns the allocated index (>= 0), with 1 (0xFFFFFFFF) if no index is available. DWORD TlsAlloc (VOID) BOOL TlsFree (DWORD dwIndex) An individual thread can get and set its values (void pointers) from its slot using a TLS index. The programmer must ensure that the TLS index parameter is validthat is, that it has been allocated with TlsAlloc and has not been freed. LPVOID TlsGetValue (DWORD dwTlsIndex)BOOL TlsSetValue (DWORD dwTlsIndex, LPVOID lpTlsValue) TLS provides a convenient mechanism for storage that is global within a thread but unavailable to other threads. Normal global storage is shared by all threads. Although no thread can access another thread's TLS, any thread can call TlsFree and destroy an index for all threads, so TlsFree should be used carefully. TLS is frequently used by DLLs as a replacement for global storage in a library; each thread, in effect, has its own global storage. TLS also provides a convenient way for a calling program to communicate with a DLL function, and this is the most common use of TLS. An example in Chapter 12 (Program 12-4) exploits TLS to build a thread-safe DLL; DLL thread and process attach/detach calls (Chapter 5) are another important element in the solution. |
TLS
最新推荐文章于 2022-06-04 15:46:11 发布