我认为 thread_local
变量是每个线程的私有(private)变量,只是名称相同。但是我发现的所有示例都使用 mutex
变量在访问它时锁定 thread_local
变量。这让我很困惑。如果thread_local
对每个线程都是私有(private)的,就没有必要处理并发问题,或者我对“私有(private)”想法的认识是错误的?
示例取自 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
变量?
最佳答案
如果你获取一个指向 thread_local 对象的指针,并将指针传递给另一个线程,在某种程度上,另一个线程仍然可以使用该指针访问原始线程的 thread_local 对象(直到原始线程终止,之后这个点成为未定义的行为)。
因此,如果这可能发生在您的应用程序中,您仍然需要安排互斥保护或类似的东西,以便以线程安全的方式访问 thread_local 对象。
关于c++ - 是否需要使用互斥锁来锁定 thread_local 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31891930/