C++ Thread-local storage


Example

Thread-local storage can be created using the thread_local keyword. A variable declared with the thread_local specifier is said to have thread storage duration.

  • Each thread in a program has its own copy of each thread-local variable.
  • A thread-local variable with function (local) scope will be initialized the first time control passes through its definition. Such a variable is implicitly static, unless declared extern.
  • A thread-local variable with namespace or class (non-local) scope will be initialized as part of thread startup.
  • Thread-local variables are destroyed upon thread termination.
  • A member of a class can only be thread-local if it is static. There will therefore be one copy of that variable per thread, rather than one copy per (thread, instance) pair.

Example:

void debug_counter() {
    thread_local int count = 0;
    Logger::log("This function has been called %d times by this thread", ++count);
}