1. 概述
1.1 __thread是GCC内置的线程局部存储设施。_thread变量每一个线程有一份独立实体,各个线程的值互不干扰。可以用来修饰那些带有全局性且值可能变,但是又不值得用全局变量保护的变量。
1.2 举例说明
__thread int count = 0;
int main()
{
//创建线程A
//创建线程B
//此时A和B线程都有一个实体 count,二者并不相同
}
2. 使用举例
#include <iostream>
#include <pthread.h>
#include <unistd.h>
__thread int i = 0;
void* f1(void* arg)
{
i++;
printf("f1 i address %p val %d\n", &i, i);
}
void* f2(void* arg)
{
i += 2;
printf("f2 i address %p val %d\n", &i, i);
}
int main()
{
pthread_t pid1, pid2;
i += 3;
pthread_create(&pid1, NULL, f1, NULL);
pthread_create(&pid2, NULL, f2, NULL);
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);
printf("main i address %p val %d\n", &i, i);
return 0;
}
结果:
注意,f1 和 f2 中的地址并不相同