CSE Roadmap

Core tier · about 4 hours · 7 parts

Part 5 of 7 · 2 min read

Thread-local storage

In plain words: Sometimes a global variable is what a program needs, but with one separate copy per thread. Thread-local storage gives exactly that. In C, the keyword __thread (or _Thread_local in C11) in front of a global or static variable makes every thread get its own copy, set to its initial value when the thread starts.

static __thread int tls = 0;
static void *bump(void *a) {
    (void)a;
    for (int i = 0; i < 1000; i++) tls++;
    printf("thread: tls = %d\n", tls);
    return NULL;
}

Three threads, started one after another, and then the main thread printed:

thread: tls = 1000
thread: tls = 1000
thread: tls = 1000
main:   tls = 0 (its own copy, never changed)

Every thread counted from 0 to 1,000 in its own copy. None of them disturbed the others and the main thread's copy stayed 0. No lock is needed, because no variable is shared.

The best known example is errno (Level 0, page 2). If errno were one global, a failed call in one thread could overwrite the code that another thread was about to read. Under POSIX it is thread-local. A test where a worker thread opens a file that does not exist showed it:

worker: open returned -1, errno = 2 (No such file or directory)
main:   errno = 0

The worker's failure set errno to 2 in the worker's copy. The main thread's errno stayed 0. This is also why the pthread functions return their error numbers directly (page 2): they have no need of the shared state.

Thread-local storage

Thread-local storage is memory that is private to one thread: a variable declared with __thread has a separate instance for each thread, and a thread can read and write only its own.

Example: errno is thread-local, so a failed system call in one thread does not change the errno seen by another.

Check yourself: 1. What does __thread do to a variable? 2. Why is errno thread-local? 3. Does a thread-local variable need a lock?