For the More Curious: Thread Local Storage

Sometimes it is very handy to have storage that is private to a thread. In the basics.m program above, you could stash the contents of the ThreadInfo stack into thread local storage instead of on the function call stack. Thread local storage behaves like global variables but are private to the thread. errno is stored in thread local storage so that every thread has its own errno.

To use thread local storage, initialize a pthread_key_t using pthread_key_create():

int pthread_key_create (pthread_key_t *key, void (*destructor)(void *));

This creates an abstract key. Usually you name a variable with a descriptive name or associate this key with a descriptive string in a dictionary, as shown in Figure 20.5 ...

Get Advanced Mac OS X Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.