Thread Local Storage
线程局部存储(tls)是一种机制,通过这一机制分配的变量,每个当前线程有一个该变量的实例.
gcc用于实现tls的运行时模型最初来自于IA-64处理器的ABI,但以后被用到其它处理器上。它需要链接器(ld),动态连接器(ld.so)和系统库(libc.so,libpthread.so)的全力支持.因此它不是到处可用的。
在用户层,用一个新的存储类型关键字:__thread表示这一扩展。例如:
__thread int i;
extern __thread struct state s;
static __thread char *p;
__thread限定符(specifier)可以单独使用,也可带有extern或static限定符,但不能带有其它存储类型的限定符。
__thread可用于全局的静态文件作用域,静态函数作用域或一个类中的静态数据成员。不能用于块作用域,自动或非静态数据成员。
当应用addressof操作符于一个线程局部存储变量时,它被在运行时求值,返回该变量当前线程实例的地址。这样得到的地址可以被其它任何线程使用。当一个线程终止时,任何该线程中的线程局部存储变量都不再有效。静态初始化不会涉及到任何线程局部存储变量的地址。
在c++中,如果一个线程局部存储变量有一个初始化器,它必须是常量表达式。 比如以下代码 #include <pthread.h> #include <iostream> using namespace std; __thread int i; void* fun1 (void* params) { i = 2; cout << pthread_self() << " before sleep " << i << endl; sleep(2); cout << pthread_self() << " after sleep " << i << endl; } void* fun2 (void* params) { i = 4; cout << pthread_self() << " before sleep " << i << endl; sleep(2); cout << pthread_self() << " after sleep " << i << endl; } int main() { pthread_t t1,t2; pthread_create(&t1,NULL,fun1,NULL); pthread_create(&t2,NULL,fun2,NULL); pthread_join(t1,NULL); pthread_join(t2,NULL); return 0; } 输出如下: 1094846784 before sleep 2 1105336640 before sleep 4 1094846784 after sleep 2 1105336640 after sleep 4 可见,不同的线程都保存了自己的local变量,在应用中,如果说一个打印日志功能的cpp文件,提 |
Thread Local Storage
最新推荐文章于 2025-03-15 10:56:24 发布