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.
我维护的库具有一个需要特定线程变量的函数。由于gcc 4.2中的一个错误,如果我在x中定义静态__thread;当通过PERL的未命名API调用库函数时,它会挂起。
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.
我想使用pthread_key_create()来定义线程本地变量,但是我需要在库中这样做,并且在创建线程时不会得到任何特殊的调用。
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.
注意:如果您想知道,我在线程中需要一个锁的原因是为了使这个函数信号安全,以及线程安全。
1 个解决方案
#1
6
To do something once use pthread_once
:
使用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.
然后,您可以从回调中安全地调用get_tls_key()来获取TLS密钥,而不必担心创建两个密钥。
#1
6
To do something once use pthread_once
:
使用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.
然后,您可以从回调中安全地调用get_tls_key()来获取TLS密钥,而不必担心创建两个密钥。