Thread-local storage
suggest changeAn object with thread storage duration has a separate instance in each thread that uses it. Its lifetime is the entire execution of that thread.
C23 spells the storage-class specifier thread_local:
thread_local unsigned request_count;
C11 through C17 use _Thread_local. Including <threads.h> in those versions may also define thread_local as a convenience macro. At block scope, combine the specifier with static or extern:
void record_request(void)
{
static thread_local unsigned request_count;
++request_count;
}
Thread-local storage does not make other shared objects safe to access concurrently. Protect shared mutable state with synchronization or use the atomic facilities from <stdatomic.h>.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents