pthread_getspecific和pthread_setspecific使用

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


  1. /* 
  2.  * ===================================================================================== 
  3.  *       Filename:  thead.c 
  4.  *    Description:  getspecific 
  5.  *        Created:  05/10/2011 12:09:43 AM 
  6.  * ===================================================================================== 
  7.  */  
  8. #include<stdio.h>  
  9. #include<pthread.h>  
  10. #include<string.h>  
  11. pthread_key_t p_key;  
  12.    
  13. void func1()  
  14. {  
  15.         int *tmp = (int*)pthread_getspecific(p_key);//同一线程内的各个函数间共享数据。  
  16.         printf("%d is runing in %s\n",*tmp,__func__);  
  17.    
  18. }  
  19. void *thread_func(void *args)  
  20. {  
  21.    
  22.         pthread_setspecific(p_key,args);  
  23.    
  24.         int *tmp = (int*)pthread_getspecific(p_key);//获得线程的私有空间  
  25.         printf("%d is runing in %s\n",*tmp,__func__);  
  26.    
  27.         *tmp = (*tmp)*100;//修改私有变量的值  
  28.    
  29.         func1();  
  30.    
  31.         return (void*)0;  
  32. }  
  33. int main()  
  34. {  
  35.         pthread_t pa, pb;  
  36.         int a=1;  
  37.         int b=2;  
  38.         pthread_key_create(&p_key,NULL);  
  39.         pthread_create(&pa, NULL,thread_func,&a);  
  40.         pthread_create(&pb, NULL,thread_func,&b);  
  41.         pthread_join(pa, NULL);  
  42.         pthread_join(pb, NULL);  
  43.         return 0;  
  44. }  

#gcc -lpthread  test.c -o test

# ./test 

2 is runing in thread_func

1 is runing in thread_func

100 is runing in func1

200 is runing in func1

猜你喜欢

转载自blog.csdn.net/u010144805/article/details/80353650