I am working on a mobile platform over Nucleus RTOS. It uses Nucleus Threading system but it doesn't have support for explicit thread local storage i.e, TlsAlloc, TlsSetValue, TlsGetValue, TlsFree APIs. The platform doesn't have user space pthreads as well.
I found that __thread storage modifier is present in most of the C++ compilers. But i don't know how to make it work for my kind of usage. How does __thread keyword can be mapped with explicit thread local storage? I read many articles but nothing is so clear for giving me the following basic information
- will __thread variable different for each thread ?
- How to write to that and read from it ? does each thread has exactly one copy of the variable ?
following is the pthread based implementation:
pthread_key_t m_key;
struct Data : Noncopyable {
Data(T* value, void* owner) : value(value), owner(owner) {}
int* value;
};
inline ThreadSpecific()
{
int error = pthread_key_create(&m_key, destroy);
if (error)
CRASH();
}
inline ~ThreadSpecific()
{
pthread_key_delete(m_key); // Does not invoke destructor functions.
}
inline T* get()
{
Data* data = static_cast<Data*>(pthread_getspecific(m_key));
return data ? data->value : 0;
}
inline void set(T* ptr)
{
ASSERT(!get());
pthread_setspecific(m_key, new Data(ptr, this));
}
How to make the above code use __thread way to set & get specific value ? where/when does the create & delete happen?
If this is not possible, how to write custom pthread_setspecific, pthread_getspecific kind of APIs.
I tried using a C++ global map and index it uniquely for each thread and retrieved data from it. But it didn't work well.