我认为thread_local
变量是每个线程的私有变量,只是名称相同。但是,我发现所有示例都使用mutex
变量在访问变量时锁定thread_local
变量。这让我困惑。如果thread_local
对于每个线程都是私有的,那么就不需要考虑并发问题,或者我对“私有”想法的承认是错误的?thread_local变量是否需要使用互斥锁定?
实施例从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();
}
在这种情况下,是否需要锁定thread_local
变量?
哪个例子?如果你显示它,我们可能会告诉你它为什么使用互斥锁,但可能有不同的原因。 –
@RaphaelMiedl我得到了一个:http://stackoverflow.com/a/15698197/2269707 – reavenisadesk
'互斥'只有通过'std :: cout'同步输出('std :: cout'不是线程安全并可以交织输出),正如名称所暗示的,它与thread_local变量无关。你可以通过输出看到thread_local变量是完全不同的。 –