TLS


Thread Local Storage

Threads 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.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值