Course contentsShow
← C
Lesson 1122 of 1,21915. Systems ProgrammingFree lesson

Thread-local storage basics

Thread-local storage basics

What you'll learn: How to use the __thread keyword to give every thread its own private instance of a global variable.

The problem with shared globals

In multithreading, global variables are usually shared property. If you have a global int counter, and ten threads increment it at once, they will trip over each other, leading to data races and wrong totals. To fix this, we usually use mutexes to "lock" the variable. However, locking takes time and slows down your program.

Sometimes, you want a global variable that isn't shared. You want a variable that is globally accessible by name, but physically unique to every thread—like a private notebook that sits on every worker's desk.

Enter Thread-Local Storage (TLS)

Thread-local storage allows you to define a variable that persists for the life of the thread, but is private to that thread. In C (specifically using GCC or Clang), we achieve this using the __thread storage class specifier.

When you mark a variable with __thread, the operating system and linker work together to create a new "copy" of that variable every time a new thread starts. Thread A can change its copy to 5, while Thread B sets its copy to 10, and neither will ever see the other’s value.

Code Example

Notice how we define the variable outside of main, just like a normal global, but with the special keyword.

#include <pthread.h>
#include <stdio.h>

// Each thread gets its own private version of this variable
__thread int thread_id_log = 0;

void* worker(void* arg) {
    int id = *((int*)arg);
    
    // Assigning to the global variable only affects THIS thread
    thread_id_log = id;
    
    printf("Thread %d says: my private log value is %d\n", id, thread_id_log);
    return NULL;
}

int main() {
    pthread_t t1, t2;
    int val1 = 1, val2 = 2;

    pthread_create(&t1, NULL, worker, &val1);
    pthread_create(&t2, NULL, worker, &val2);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    return 0;
}

Why use it?

TLS is perfect for things like error codes (e.g., errno) or random number generators where each thread needs its own independent state. It gives you the convenience of a global variable without the headache of synchronization or the risk of threads overwriting each other's data.

Key takeaway

The __thread keyword creates "private globals" that exist independently for every thread, preventing data races without the need for expensive mutex locks.