How do I create a global variable that is thread-specific in C using POSIX threads?

后端 未结 3 772
[愿得一人]
[愿得一人] 2021-01-31 21:32

I am learning about POSIX threads and I have come to the section on Thread Specific Data. The book does an excellent example using a file descriptor. However, I wanted to do the

3条回答
  •  攒了一身酷
    2021-01-31 21:39

    This is not an answer, but a side note:

    If you are working on Linux-specific code, you can use the __thread keyword. Essentially,

    static __thread int counter = 5;
    

    creates a different counter variable for each thread, initialized to value 5 whenever a new thread gets created. Such code is future-compatible with C11, since C11 standardized the same semantics using the _Thread_local keyword. This is much saner than the POSIX thread-specific functions (which have implementation-specific limits, and are quite cumbersome compared to the __thread keyword), on all architectures using C, except those that have declared C99 and later "standard non grata" (i.e., Microsoft).

    See the Thread-Local Storage chapter in GCC documentation for details.

提交回复
热议问题