I considered thread_local
variables as private variables for each thread, just with the same name. But all examples I found use a mutex
variable to lock the thread_local
variable when accessing it. This confused me. If thread_local
is private for each thread, there is no need to take care of the concurrency problem, or my acknowledgement of the "private" idea is wrong?
Example taken from here:
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
thread_local unsigned int rage = 1;
std::mutex cout_mutex;
void increase_rage(const std::string& thread_name)
{
++rage;
std::lock_guard<std::mutex> lock(cout_mutex);
std::cout << "Rage counter for " << thread_name << ": " << rage << '\n';
}
int main()
{
std::thread a(increase_rage, "a"), b(increase_rage, "b");
increase_rage("main");
a.join();
b.join();
}
In this case, is it necessary to lock the thread_local
variable?