One of my favorite GCC extensions is the __thread keyword, which declares a global variable to be in a portion of the data segment that’s copied on every thread-creation operation. You can use __thread to allocate structures and variables on a per-thread basis—very useful for making functions thread-safe. Accessing static variables in a thread-safe way requires locking. Often, however, static variables are just used to cache some information between calls. It doesn’t matter that they aren’t globally unique (and sometimes it isn’t even desirable).
For portable code, you typically have to use the POSIX thread-local storage functions, but they have a couple of limitations:
- They only store pointers, so anything larger than 4 or 8 bytes (depending on your system) has to be heap-allocated, and you need to add manual cleanup code even for simple data types.
- The compiler doesn’t know anything about these values, and therefore can’t optimize.
Typically, one register is used to store a pointer to the current thread’s local storage area, and the POSIX routines just give you an offset within this region. The __thread storage class allows you to create static variables within this segment.