I’m maintaining a library that has a function that needs thread specific variables.
Due to a bug in gcc 4.2, if I define
static __thread in x;
when the library function is called via unnamed API from PERL, it hangs.
I’d like to define the thread local variables using pthread_key_create(), but I need to do it
in the library, and I don’t get any special call when a thread is created.
How do I create a thread local variable, only if it does not exist?
Something like
pthread_key_t tlsKey = 0;
int x;
myfunc()
{
if (pthread_key_t == 0){
pthread_key_create(&tlsKey, NULL);
pthread_setspecific(tlsKey, &x);
}
int& myx = pthread_getspecific(tlskey);
if (myx == 0){
myx=1;
something_under_myx_lock();
myx = 0;
} else {
cout << "locked in thread\n";
}
}
Note: if you wonder, the reason I need a lock within the thread is to make this function signal safe, as well as thread safe.
To do something once use
pthread_once:You can then call
get_tls_key()safely from your callback to get the TLS key without worrying about creating two keys.