【问题标题】:How to create pthread specific variables without __thread如何在没有 __thread 的情况下创建 pthread 特定变量
【发布时间】:2011-07-04 08:35:02
【问题描述】:

我正在维护一个库,该库具有需要线程特定变量的函数。 由于 gcc 4.2 中的错误,如果我定义 x中的静态__thread; 当库函数通过 PERL 中的未命名 API 调用时,它会挂起。

我想使用 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";
    }

}

注意:如果您想知道,我需要在线程内加锁的原因是为了使这个函数信号安全,以及线程安全。

【问题讨论】:

    标签: c++ pthreads


    【解决方案1】:

    做某事一次使用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 密钥,而无需担心创建两个密钥。

    【讨论】:

    • 问题被标记为“C++”,所以我假设提问者使用的是 C++ 编译器。 pthread_once 是一个 C 函数,并且期望传递的函数是指向 C 函数的指针。 C++ 和 C 函数不一定具有相同的调用约定/ABI,因此extern "C" 在技术上是必要的。在某些编译器/平台上,它可以省略。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多