With gcc, you can use __thread to declare a local thread variable. However, this is limited to POD types with constant initializers and is not necessarily available on all platforms (although it is available for both Linux and Windows). You use it as part of a variable declaration, since you would use thread_local :
__thread int i=0; i=6;
On POSIX systems, you can use pthread_key_create and pthread_[sg]et_specific to access local thread data that you manage yourself, and on Windows you can use TlsAlloc and Tls[GS]etValue to the same end.
Some libraries provide wrappers for them that allow you to use types with constructors and destructors. For example, boost provides boost::thread_specific_ptr , which allows you to store a dynamically allocated object that is local to each thread, and my just :: thread provides a JSS_THREAD_LOCAL macro that accurately mimics the behavior of the thread_local keyword from C ++ 0x.
eg. using boost:
boost::thread_specific_ptr<std::string> s; s.reset(new std::string("hello"));
or using only :: thread:
JSS_THREAD_LOCAL(std::string,s,("hello")); // s is initialised to "hello" on each thread s+=" world"; // value can be used just as any other variable of its type std::string* ps=&s; // take a pointer to the value for the current thread
source share