pthread_getspecific()和pthread_setspecific()的使用方法

来源:互联网 发布:美工岗位职责是那些 编辑:程序博客网 时间:2024/05/21 11:13

pthread_getpecific和pthread_setspecific实现同一个线程中不同函数间共享数据的一种很好的方式。

#include <stdio.h>#include <stdlib.h>#include <pthread.h>pthread_key_t key;void func1(){int *tmp = (int*)pthread_getspecific(key);printf("%d is fun is %s\r\n",*tmp,__func__);}void *tthread_fun(void* args){pthread_setspecific(key,args);int *tmp = (int*)pthread_getspecific(key);printf("%d is in zhu %s\r\n",*(int*)args,__func__);*tmp+=1;func1();return (void*)0;}void *thread_fun(void *args){pthread_setspecific(key,args);int *tmp = (int*)pthread_getspecific(key);//获得线程的私有空间printf("%d is runing in %s\n",*tmp,__func__);*tmp = (*tmp)*100;//修改私有变量的值func1();return (void*)0;}int main(){pthread_t pa, pb;pthread_key_create(&key,NULL);pthread_t pid[3];int a[3]={100,200,300};int i=0;for(i=0;i<3;i++){pthread_create(&pid[i],NULL,tthread_fun,&a[i]);pthread_join(pid[i],NULL);}return 0;}