Can you use thread local variables inside a class or structure

后端 未结 9 1840
名媛妹妹
名媛妹妹 2020-12-30 23:34

Like this.

struct some_struct
{
 // Other fields
 .....
 __thread int tl;
}

I\'m trying to do that but the compiler is giving me this error

相关标签:
9条回答
  • 2020-12-31 00:24

    For C this makes not much sense, static (= global) members are only a feature of C++. And so the new C11 standard (that introduces _Thread_local) doesn't allow it. These beast are allowed basically everywhere were a variable with static storage duration is allowed.

    For C++ this could make sense inside a class as analogous to a static member, but if this is allowed by C++11 I have no idea.

    0 讨论(0)
  • 2020-12-31 00:33

    You can also specify the struct itself as thread local. For example;

    #include <pthread.h>
    
    thread_local struct gl_i_t{
        int a; 
        int b;
    }GL_i_t;
    

    Then you can use GL_i_t variables inside thread.

    0 讨论(0)
  • 2020-12-31 00:35

    C11 standard Section 6.7.1 Paragraph 2

    At most, one storage-class specifier may be given in the declaration specifiers in a declaration, except that _Thread_local may appear with static or extern.120)

    C11 standard Section 6.7.1 Paragraph 3

    In the declaration of an object with block scope, if the declaration specifiers include _Thread_local, they shall also include either static or extern. If _Thread_local appears in any declaration of an object, it shall be present in every declaration of that object.

    0 讨论(0)
提交回复
热议问题