Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create pthread specific variables without __thread

Tags:

c++

pthreads

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.

like image 772
dbbd Avatar asked Jul 04 '11 08:07

dbbd


1 Answers

To do something once use pthread_once:

pthread_key_t tls_key;
pthread_once_t tls_init_flag=PTHREAD_ONCE_INIT;

extern "C"
{
    static void tls_destructor(void*); // run when thread exits to cleanup TLS data
    static void create_tls_key()
    {
        if(pthread_key_create(&tls_key,tls_destructor))
        {
            abort();
        }
    }
}

pthread_key_t get_tls_key()
{
    pthread_once(&tls_init_flag,create_tls_key);
    return tls_key;
}

You can then call get_tls_key() safely from your callback to get the TLS key without worrying about creating two keys.

like image 73
Anthony Williams Avatar answered Oct 23 '22 10:10

Anthony Williams