POSIX线程私有数据

在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);


测试代码:

//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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值