C++-thread_local关键词

简介

thread_local 为 C++11 引入的关键词,能搭配声明于命名空间作用域的对象、声明于块作用域的对象及静态数据成员。

它指示对象具有线程存储期。

它能与 static 或 extern 结合,以分别指定内部或外部链接(但静态数据成员始终拥有外部链接),但额外的 static 不影响存储期

被其声明的变量的存储存储期为线程(thread)存储期

使用

thread_local 关键字修饰的变量在线程开始的时候被生成,在线程结束的时候被销毁

并且每一个线程都拥有一个独立的变量实例

并且注意,thread_local 只是改变了变量的存储周期,而没有改变其作用域

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void foo()
{
thread_local int a = 0;
printf("id=%d, n=%d\n", std::this_thread::get_id(), a);
a++;
}
void fun()
{
foo();
foo();
foo();
}
int main()
{
thread t1(fun);
thread t2(fun);
t1.join();
t2.join();
return 0;
}

此示例输出为

1
2
3
4
5
6
id=12404, n=0
id=12404, n=1
id=12404, n=2
id=15720, n=0
id=15720, n=1
id=15720, n=2