【发布时间】:2015-10-31 17:40:51
【问题描述】:
我将thread_local 变量视为每个线程的私有变量,只是名称相同。但是我发现的所有示例都使用mutex 变量在访问它时锁定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 我得到了一个:stackoverflow.com/a/15698197/2269707
-
mutex只是通过std::cout同步输出(std::cout不是线程安全的,可以交错输出),顾名思义,它与线程局部变量。您可以通过输出看到 thread_local 变量是完全不同的。 -
互斥体也被锁定之后
++rage,thread_local 变量根本没有受到保护,也不需要。 -
是的,
thread_local变量不需要同步。在您的示例中,互斥锁绝对只对 cout 是必需的。
标签: c++ multithreading