For local variables, each time a function is called by different threads, a new copy of the variable is obtained on the stack,
Global and static variables have only one entity. MFC provides a mechanism to define them just like global variables.
Thread Local data. The so-called Thread Local data means that each thread accessing them will have a copy that only belongs to the thread.
You can use the macro THREAD_LOCAL (class_name, ident_name) to define the local data of a thread. THREAD_LOCAL is defined as follows:
# Define THREAD_LOCAL (class_name, ident_name )/
AFX_DATADEF CThreadLocal <class_name> ident_name;
AFX_DATADEF is a placeholder, class_name is the type of local data of the thread, and ident_name is the name of local data of the thread,
Class_name must be derived from CNoTrackObject.
Example:
Struct CMyThreadData: public CNoTrackObject
{
CString strThread;
};
THREAD_LOCAL (CMyThreadData, threadData)
The above line is equivalent
CThreadLocal <CMyThreadData> threadData;
ThreadData is defined as the local data of a thread. In fact, threadData is still global, not a local data of a real thread,
All of its members are genuine Thread Local data, no matter how many threads access threadData-> strThread will get
One copy only belongs to its own copy. These copies are actually allocated to the heap, And the allocation process occurs when each thread is accessed for the first time.
CThreadLocal reloads operator->. When each thread accesses its members for the first time, it will create a new CMyThreadData and place it on the stack.
What does CThreadLocal rely on? Remember which CMyThreadData on the stack belongs to which thread? The answer is TLS.
CThreadLocal is derived from CThreadLocalObject. CThreadLocalObject has a member m_nSlot,
Each CThreadLocalObject sub-object defined by THREAD_LOCAL has a unique value.