Use thread local data TLS in MFC

zhaozj2021-02-16  49

For local variables, different threads will get a new copy of the variable on the stack every time the function, the global and static variables provide only one entity, and the MFC provides a mechanism, making it like definition global The variables are the same as the thread local data, so that the wires are all copied to each of the threads that access their threads.

The thread local data can be defined using macro thread_local (class_name, ident_name), thread_local is defined as follows:

#define thread_local (class_name, Ident_name) / AFX_DATADEF CTHREADLOCAL Ident_name;

The AFX_DATADEF is a placeholder, class_name is the type of thread local data, and Ident_Name is the name of the thread local data, and the class_name must be derived from CNotrackObject.

Example: Struct CMYTHREADDATA: PUBLIC CNOTRACKOBJECT {CSTRING STRTHREAD;

Thread_local (CMYTHREADDATA, ThreadData) This line is equivalent to CThreadLocal ThreadData; defines thread local data ThreadData, in fact ThreadData is still global, not true threads, but all of its members are trimming threads Data, no matter how many threads access ThreadData-> strathread will receive a copy that only belongs to its own, which is actually assigned in the heap, and the allocation process occurs when each thread is first accessed.

CTHREADLOCAL overloads Operator->, when each thread visits its members, it will new CMYTHREADDATA is put on a pile, and that CTHREADLOCAL is what CMYTHREADDATA remembers on the pile which thread is it? The answer is TLS.

Cthreadlocal is derived from CTHREADLOCALOBJECT, and CThreadLocalObject has a member m_nslot, which has a unique value for each CTHREADLOCALOBJECT sub-object generated by Thread_local.

转载请注明原文地址:https://www.9cbs.com/read-21275.html

New Post(0)