在JAVA中是使用ThreadLocal来实现线程特定数据。POSIX中操作线程私有数据的主要通过以下4个函数来实现:pthread_key_create(创建一个键),pthread_setspecific(为一个键设置线程私有数据),pthread_getspecific(从一个键读取线程私有数据),pthread_key_delete(删除一个键)。这几个函数的声明如下:
#include <pthread.h>
int pthread_key_create(pthread_key_t *key,void (*destr_function)(void *));
int pthread_setspecific(pthread_key_t key,const void *pointer));
void *pthread_getspecific(pthread_key_t key);
int pthread_key_delete(pthread_key_t key);
测试代码:
编译:gcc -o pthread_data2 pthread_data2.c -l pthread
运行:
./pthread_data2
main thread begins running
thread -1216165008 is running
thread -1216165008 returns 100
thread -1224557712 is running
thread -1224557712 returns 200
thread -1216165008 returns 100
thread -1224557712 returns 200
thread -1224557712 returns 200
thread -1216165008 returns 100
thread -1224557712 returns 200
thread -1216165008 returns 100
thread -1224557712 returns 200
thread -1216165008 returns 100
main thread exit
#include <pthread.h>
int pthread_key_create(pthread_key_t *key,void (*destr_function)(void *));
int pthread_setspecific(pthread_key_t key,const void *pointer));
void *pthread_getspecific(pthread_key_t key);
int pthread_key_delete(pthread_key_t key);
测试代码:
//pthread_data2.c
#include <stdio.h>
#include <string.h>
#include <pthread.h>
pthread_key_t key;
void * mythread(void* arg){
int tsd = *(int*)arg;
printf("thread %d is running\n",pthread_self());
pthread_setspecific(key,(void *)tsd);
int i = 0;
for(i=0; i<5; i++){
printf("thread %d returns %d\n",pthread_self(),pthread_getspecific(key));
sleep(1);
}
}
int main(void){
pthread_t thid1;
pthread_t thid2;
printf("main thread begins running\n");
pthread_key_create(&key,NULL);
int i = 100;
pthread_create(&thid1,NULL,mythread,&i);
int j = 200;
pthread_create(&thid2,NULL,mythread,&j);
sleep(5);
pthread_key_delete(key);
printf("main thread exit\n");
return 0;
}
编译:gcc -o pthread_data2 pthread_data2.c -l pthread
运行:
./pthread_data2
main thread begins running
thread -1216165008 is running
thread -1216165008 returns 100
thread -1224557712 is running
thread -1224557712 returns 200
thread -1216165008 returns 100
thread -1224557712 returns 200
thread -1224557712 returns 200
thread -1216165008 returns 100
thread -1224557712 returns 200
thread -1216165008 returns 100
thread -1224557712 returns 200
thread -1216165008 returns 100
main thread exit