Use thread local data tls in mfc

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.