[英]Do thread_local variables need to be locked using a mutex?
I considered thread_local
variables as private variables for each thread, just with the same name. 我将
thread_local
变量视为每个线程的私有变量,只是名称相同。 But all examples I found use a mutex
variable to lock the thread_local
variable when accessing it. 但是我发现的所有示例在访问它时都使用
mutex
变量来锁定thread_local
变量。 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? 如果
thread_local
对每个线程都是私有的,则无需照顾并发问题,或者我对“私有”想法的认可是错误的?
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? 在这种情况下,是否有必要锁定
thread_local
变量?
If you take a pointer to a thread_local object, and pass the pointer to another thread, in some way, the other thread can still access the original thread's thread_local object using the pointer (until the originating thread terminates, after which point this becames undefined behavior). 如果您使用一个指向thread_local对象的指针,并将该指针传递给另一个线程,则在某种程度上,另一个线程仍然可以使用该指针访问原始线程的thread_local对象(直到发起线程终止,此后这变成未定义的行为) )。
So, if this can happen in your application, you will still need to arrange for mutex protection, or something equivalent, in order to access the thread_local object in a thread-safe manner. 因此,如果这可能在您的应用程序中发生,则您仍将需要安排互斥保护或等效保护,以便以线程安全的方式访问thread_local对象。
Naming thread_local
variables private variables is a bit unfortunate. 命名
thread_local
变量私有变量有点不幸。
A thread_local
declared variable is owned by its thread
and not accessible by other thread
s unless the owner thread
(for some reason) gives them a pointer to that variable. 声明的
thread_local
变量由其thread
拥有,并且其他thread
无法访问,除非所有者thread
(由于某种原因)为它们提供了指向该变量的指针。 A thread_local
variable is shared among all functions of its thread; thread_local
变量在其线程的所有功能之间共享; ie it has its lifetime. 即它有它的寿命。 If a
thread_local
variable is constructed it will be destroyed when its thread
exits. 如果构造了
thread_local
变量,则在其thread
退出时将销毁它。
A thread_local
variable can be static, in which case some care should be taken to make sure the program executes as expected. thread_local
变量可以是静态的,在这种情况下,应注意确保程序按预期执行。 I won't go into this, since it is not part of the question. 我将不讨论这个问题,因为这不是问题的一部分。
The mutex
in your example, as pointed out in the comments, is not for a data race condition. 如注释中所指出,示例中的
mutex
不适用于数据争用条件。 It is to synchronize the console output: the mutex
is called cout_mutex
- self explaining. 这是为了同步控制台输出:
mutex
称为cout_mutex
自解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.