线程存储原理:为变量在每一个现存的线程里分配一个实例,需要处理器支持,并不是所有都支持!支持全局的,静态的变量,但不支持局部变量。
关键字
__thread
__thread int i;
extern __thread struct state s;
static __thread char *p;
测试
#include<pthread.h> #include<unistd.h> #include<string.h> #include <stdio.h> __thread int var=1; typedef struct context_t { int p1; char name[256]; }context; __thread context ctx; void product(char *name) { static __thread int i = 0; printf("--->%s:%d ",name, ++i); } void* worker1(void*arg); void* worker2(void*arg); int main() { pthread_t pid1,pid2; memset(&ctx, 0, sizeof(context)); ctx.p1 = 11; strcpy(ctx.name, "null"); pthread_create(&pid1,NULL,worker1,NULL); pthread_create(&pid2,NULL,worker2,NULL); pthread_join(pid1,NULL); pthread_join(pid2,NULL); printf("exit, var:%d, p1:%d, name=%s ",var,ctx.p1, ctx.name); return 0; } void* worker1(void* arg)
{ strcpy(ctx.name, "lilei"); ctx.p1=1; printf("work1:%d ", ++var); printf("work1:%d, name=%s ", ctx.p1, ctx.name); product("work1"); } void* worker2(void* arg)
{ sleep(5); printf("work2:%d ", ++var); printf("work2:%d, name=%s ", ctx.p1, ctx.name); product("work2"); }
输出结果:
[root@localhost test]# gcc -lpthread -o test test.c [root@localhost test]# ./test work1:2 work1:1, name=lilei --->work1:1 work2:2 work2:0, name= --->work2:1 exit, var:1, p1:11, name=null
可以看出多个线程调用,但是var,ctx, i变量值显示都是线程独立的。
参考 http://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Thread_002dLocal.html
另一种 TLS 通过pthread_key_create实现 http://www.cnblogs.com/gogly/articles/2416362.html