thread_local
implies static
when static
is omitted.
A local static
variable preserves its value when a given function is called multiple times. You may read about static
variable elsewhere.
Now, I assume you do know what static
variable is - the important things are just:
- static variables have local scope
- (but) static variables have global existence
The second point makes a static variable's memory accessible to other functions by C++ references and pointers - it proves that the static variable has just one copy - across all threads of the process. You need to know what threads are and how to create/program threads.
Now, to the question. You know that Global variables have global scope and global accessibility, but when you run two or more instances of your program, both/all of them would have a SEPARATE copy of that global variable. That means each process would have a separate copy of that global variable.
So, what if you wanted to have a SEPARATE copy of static
variable per thread? You use thread_static
. Each thread will have a separate copy of that static variable.
Interestingly, you can apply thread_local
to global variables also - thence each thread will receive a separate copy of those global variables also!
// Globals
int counter;
thread_local int this_thread_counter; // Each thread will have separate copy
Now, think how strtok
would work - think about the (concurrent) calls to strtok
!