Thread Local Storage, is thread_local keyword a must?

704 views Asked by At

I'm trying to understand this concept.

Is the keyword thread_local or __declspec(thread) a must?

In the Using Thread Local Storage on MSDN, why is the variable dwTlsIndex not decorated with thread_local or __declspec(thread)?

1

There are 1 answers

0
Remy Lebeau On BEST ANSWER

dwTlsIndex itself is not stored in any thread-local memory, that is why it is not marked as thread_local or __declspec(thread).

The purpose of those keywords is to declare a separate copy of a given variable within each running thread. dwTlsIndex is not meant to be copied that way. It is a global variable initialized 1 time at program startup, via TlsAlloc(), and then shared equally by all running threads. So it can't itself be stored in thread-local memory.

Each thread has its own local array of thread-local memory slots. dwTlsIndex specifies the index of a given slot (variable) within those arrays. The index of a given variable stored in thread-local memory is the same for all threads. By sharing dwTlsIndex globally, all threads know which slot to access for that variable.

Read Microsoft's documentation for more details about how Thread Local Storage actually works. You are focusing on a particular code example and not paying attention to the larger picture.