【C++】thread_local
1. 背景
-
thread_local 是 C++11 引入的一个关键字,用于声明线程局部存储(Thread-Local Storage,TLS)。
它用于为每个线程分配独立的变量副本,确保每个线程访问到的变量是独立的,互不干扰。
每个线程的副本是独立的,修改一个线程中的副本不会影响其他线程的副本。
这在多线程编程中非常有用,尤其是在需要为每个线程维护独立状态时。
使用 thread_local 可能会增加线程的创建和销毁开销,因为需要为每个线程分配独立的存储空间。 -
在多线程程序中,访问共享资源(如全局变量或静态变量)可能会导致竞争条件。使用 thread_local 可以为每个线程提供独立的副本,从而避免竞争。
-
在某些情况下,线程可能需要根据特定的配置参数运行。使用 thread_local 可以为每个线程提供独立的配置参数,而无需在每个线程中传递参数。
2. 声明方法
- 声明全局变量,静态成员变量
全局或静态 thread_local 变量:它们的生命周期与整个程序的生命周期相同,但在每个线程中都有独立的副本。
它们会在程序启动时初始化。
// 全局变量
thread_local int global_tls_var = 42;
// 静态成员变量
class MyClass {
public:
static thread_local int static_tls_var = 100;
};
- 声明局部变量
如果 thread_local 变量是局部变量,它们会在第一次访问时初始化。
// 局部变量
void myFunction() {
thread_local int local_tls_var = 10;
std::cout << "Local TLS var: " << local_tls_var << std::endl;
}
3. demo
#include <iostream>
#include <thread>
#include <vector>
// 全局线程局部变量
thread_local int global_tls_var = 0;
void threadFunction(int id)
{
// 局部线程局部变量
thread_local int local_tls_var = 0;
local_tls_var += 2;
std::cout << "Thread " << id << " - Global TLS1 var: " << global_tls_var << std::endl;
std::cout << "Thread " << id << " - Local TLS1 var: " << local_tls_var << std::endl;
// 访问全局线程局部变量
global_tls_var++;
std::cout << "Thread " << id << " - Global TLS2 var: " << global_tls_var << std::endl;
}
int main() {
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(threadFunction, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}

浙公网安备 33010602011771号