Re: thread local variable

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



"bangwo" <bangwo@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message
news:B77E7676-37A9-49E0-9163-822CC7A888BA@xxxxxxxxxxxxxxxx
to make the nextBuf and workBuf in the following code multi-thread save,
is it correct to replace "static" with "__declspec(thread)" in the code?
or it should be "__declspec(thread) static" ? THANKS FOR THE HELP!
------
static int nextBuf ;
static char workBuf[8][64] ;
char * GetBuf()
{
nextBuf++ ;
if( nextBuf >= 8 ) nextBuf = 0 ;
return workBuf[nextBuf] ;
}


Do you want each thread to have its own variables or do you want all threads
to share the same 2 variables?

// Each thread gets its own
static int __declspec(thread) nextBuf = 0;
static char __declspec(thread) workBuf[8][64] ;

// Shared by all threads
// To make them thread safe you need t use synchronization!
static int nextBuf = 0;
static char workBuf[8][64] ;

Mark
--
Mark Salsbery
Microsoft MVP - Visual C++



.