c++11 thread_local 变量类型
从c++11开始,c++语言层提供对线程的定义。从此c++多线程编程有了新的面貌。
c++11从定义了语言层的多线程内存模型。其中使用新增的thread_local变量修饰关键字来定义变量,可以使用该变量只属于访问它的线程,且每个能访问它的线程都会单独为该变量分配内存。
c++11以后可以变量的存储周期有:
-
auto
- automatic storage duration. (until C++11)register
- automatic storage duration. Also hints to the compiler to place the object in the processor's register. (deprecated) (until C++17)static
- static or thread storage duration and internal linkage.extern
- static or thread storage duration and external linkage.thread_local
- thread storage duration. (since C++11)
-
mutable
- does not affect storage duration or linkage. See const/volatile for the explanation.
thread_local能修饰哪些变量呢?
1. 全局变量可以被修饰: thread_local int a=0;
2. 类静态成员变量; class A{ static thread_local int a;}; thrad_local A::a=0; (注意类普通成员变量不能被thread_local修饰)
3. 函数体内的局部变量
被thread_local修饰后的变量,从属于访问它的线程,线程第一次访问它时创建它且只创建一次(与被static的修饰的变量是一样的,多实例共享一份),线程结束时系统释放该变量。
----------------------------------------
email: vimcpp@163.com
powered by igcc.cc using cpp
----------------------------------------
email: vimcpp@163.com
powered by igcc.cc using cpp
----------------------------------------