C ++ ThreadLocal Implementation

Does anyone know how best to implement ThreadLocal in C ++, whereby we can set and get the values ​​passed as needed.

I read about ThreaLocal on Wikipedia and it says:

C ++ 0x introduces the thread_local keyword. In addition, various C ++ compiler implementations provide specific ways to declare thread-local variables:

Does anyone know a gcc declaration for this and maybe its use?

+4
source share
4 answers

This is usually part of any thread library used by your OS. On Linux, local thread storage is handled by the functions pthread_key_create , pthread_get_specific and pthread_set_specific . Most thread libraries will encapsulate this, although they do offer a C ++ interface. In Boost, this is thread_specific_ptr ...

+3
source

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; // modify i for the current thread int* pi=&i; // take a pointer to the value for the current thread 

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")); // this value is local to the current thread *s+=" world"; // modify the value for the current thread std::string* ps=s.get(); // take a pointer to the value for the current thread 

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 
+3
source

VC10 has a new class called combinable which gives you the same thing with more flexibility.

+2
source

In MSVC, it is called __declspec(thread) instead of thread_local .

See http://msdn.microsoft.com/en-us/library/9w1sdazb(v=vs.80).aspx

+1
source

All Articles