Simple analysis and use of Thread Local Storage (TLS)
In multi-threaded programming, if multiple threads need to share access to the same variable, the variable can be declared using the keyword volatile. If a variable does not want to share access among multiple threads, so what should we do? Ha, this method is TLS, local thread storage. it is very simple to use, as long as the variable Declaration uses _ declspec (thread) OK. the following is an example. I believe that you will soon be able to understand its "Mysteries" based on comments.
# Include "stdafx. H"
# Include <stdio. h>
_ Declspec (thread) int g_ndata = 0; // This is the variable to be accessed by both threads.
DWORD winapi threadproc (lpvoid lpparameter)
{
G_ndata = 5;
// The secondary thread sleep for 100 ms to ensure the g_ndata = 10 of the main thread. The statement is successfully executed.
Sleep (100 );
Char szmsg [40] = {0 };
Sprintf (szmsg, "auxi thread, g_ndata: % d", g_ndata );
MessageBox (null, szmsg, "auxithread", mb_iconinformation );
Return 0;
}
Int apientry winmain (hinstance,
Hinstance hprevinstance,
Lpstr lpcmdline,
Int ncmdshow)
{
// Todo: Place code here.
DWORD dwid;
// Create a thread and start it immediately
Handle hthread = createthread (null, 1024, threadproc, null, 0, & dwid );
Assert (hthread );
// The main thread sleeps for 50 ms to ensure g_ndata = 5 of the secondary thread. The statement is successfully executed.
Sleep (50 );
G_ndata = 10;
Char szmsg [40] = {0 };
Sprintf (szmsg, "Result: % d", g_ndata );
MessageBox (null, szmsg, "mainthread", mb_iconinformation );
Return 0;
}
When you compile and run this program, you will find that if TLS is not used, the result will be 10. If TLS is used, the main thread will not affect the result of the Helper thread. now you should know what TLS is. J
Of course, for more complex TLS, you need to use Windows TLS APIs: tlsalloc, tlsfree, tlssetvalue, and tlsgetvalue. In addition, you need to synchronize mutex.