线程存储原理:为变量在每一个现存的线程里分配一个实例,需要处理器支持,并不是所有都支持!支持全局的,静态的变量,但不支持局部变量。
关键字
__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=; typedef struct context_t
{
int p1;
char name[];
}context; __thread context ctx; void product(char *name)
{
static __thread int i = ;
printf("--->%s:%d\n",name, ++i);
} void* worker1(void*arg);
void* worker2(void*arg); int main()
{
pthread_t pid1,pid2;
memset(&ctx, , sizeof(context));
ctx.p1 = ;
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 \n",var,ctx.p1, ctx.name); return ;
}
void* worker1(void* arg)
{
strcpy(ctx.name, "lilei");
ctx.p1=;
printf("work1:%d \n", ++var);
printf("work1:%d, name=%s\n", ctx.p1, ctx.name);
product("work1");
}
void* worker2(void* arg)
{
sleep();
printf("work2:%d \n", ++var);
printf("work2:%d, name=%s\n", ctx.p1, ctx.name);
product("work2");
}
输出结果:
[root@localhost test]# gcc -lpthread -o test test.c
[root@localhost test]# ./test
work1:
work1:, name=lilei
--->work1:
work2:
work2:, name=
--->work2:
exit, var:, p1:, 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