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
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.