Thread Local Storage (TLS) Simple Analysis and Use
In multi-thread programming, the same variable, if you want multiple threads to share access, then this variable can be declared using keyword volatile; then if a variable does not want to share multiple threads, then what should I do? Oh, This approach is TLS, thread local storage. It is very simple to use, as long as it is using __declspec (thread) to the variable. Let me give an example, combine the comment, I believe that everyone can know the mystery immediately "
#include "stdafx.h"
#include
__declspec (thread) int g_ndata = 0; // This is the variable to be accessed by both threads
DWORD WINAPI ThreadProc (LPVOID LPPARETER)
{
g_ndata = 5;
// Auxiliary thread sleep 100ms, guarantee the g_ndata = 10 of the main thread; the statement is successful
Sleep (100);
Char szmsg [40] = {0};
Sprintf (SZMSG, "Auxi Thread, g_ndata:% d", g_ndata);
MessageBox (Null, Szmsg, "Auxithread", MB_ICONITIONFORMATION;
Return 0;
}
Int apientry Winmain (Hinstance 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);
// Main thread sleep 50ms, guarantee the g_ndata = 5 of the secondary thread;
Sleep (50);
g_ndata = 10;
Char szmsg [40] = {0};
Sprintf (SZMSG, "Result:% D", G_NDATA);
MessageBox (Null, Szmsg, "MAINTHREAD", MB_ICONITIONFORMATION
Return 0;
}
If you compile this program, you will find that if you don't use TLS, then the result is 10; if you use TLS, then the Lord, the result of the help thread will all affect each other. How do you know how TLS is taken? J
Of course, more complex TLS will need to use the API of Windows TLS: TLSalloc, TlsFree, TLSSetValue, TLSGetValue; further needs synchronous mutual exclusion.