Thread-local storage
suggest changeThread-local storage can be created using the thread_local keyword (since C++11). 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 scope, or a static data member, is initialized before its first use on that thread. The implementation chooses whether that happens at thread startup or is deferred until first use.
- 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);
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents