![](/img/trans.png)
[英]How to call main thread in the child thread created by pthread_create?
[英]How to create pthread specific variables without __thread
我正在維護一個庫,它有一個需要線程特定變量的 function。 由於 gcc 4.2 中的錯誤,如果我在 x 中定義 static __thread; 當庫 function 通過未命名的 API 從 PERL 調用時,它掛起。
我想使用 pthread_key_create() 定義線程局部變量,但是我需要在庫中進行,並且在創建線程時我沒有得到任何特殊調用。
如何創建線程局部變量,僅當它不存在時? 就像是
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";
}
}
注意:如果您想知道,我需要在線程內鎖定的原因是為了使這個 function 信號安全,以及線程安全。
使用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;
}
然后,您可以從回調中安全地調用get_tls_key()
來獲取 TLS 密鑰,而不必擔心創建兩個密鑰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.