1,线程的私有数据:
点击打开链接
线程要有私有数据的原因:1,有时候需要维护基于每个线程的数据,2,让基于进程的接口适应多线程环境,
线程私有数据的实现方式:
线程私有数据采用了一种一键多值的技术,即一个键对应多个数值。键可以被进程内的所有线程访问,但是每个
线程把这个键与不同的线程私有数据的地址关联。
   int pthread_key_create(pthread_key_t *key, void (*destr_function) (void*));
   int pthread_key_delete(pthread_key_t key);
键一旦创建,可以通过以下两个函数将键和线程的私有数据关联
   pthread_setspecific:该函数将pointer的值(不是内容)与key相关联。用pthread_setspecific为一个键指定新的线程数据时,线程必须先释放原有的线程数据用以回收空间。
   pthread_getspecific:通过该函数得到与key相关联的数据。
   
 具体示例程序如下:

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
    1. #include <stdio.h>  
    2. #include <string.h>  
    3. #include <pthread.h>  
    4. int my_errno = 0;  
    5. pthread_key_t key;  
    6. void print_errno(char *str)  
    7. {  
    8.     printf("%s my_errno:%d\n",str, my_errno);  
    9. }  
    10. void *thread2(void *arg)  
    11. {  
    12.     printf("thread2 %ld is running\n",pthread_self());  
    13.     pthread_setspecific(key, (void *)my_errno);  
    14.     printf("thread2 %ld returns %d\n",pthread_self(),\  
    15.             pthread_getspecific(key));  
    16.     my_errno = 2;      
    17.     print_errno("thread2");  
    18. }  
    19. void *thread1(void *arg)  
    20. {  
    21.     pthread_t thid2;  
    22.     printf("thread1 %ld is running\n",pthread_self());  
    23.     pthread_setspecific(key, (void *)my_errno);  
    24.     my_errno = 1;  
    25.     pthread_create(&thid2, NULL, thread2, NULL);  
    26.     sleep(2);  
    27.     printf("thread1 %ld returns %d\n",pthread_self(),\  
    28.          pthread_getspecific(key));  
    29.     print_errno("thread1");  
    30. }  
    31. void destr(void *arg)  
    32. {  
    33.     printf("destroy memory\n");  
    34. }  
    35. int main(void)  
    36. {  
    37.     pthread_t thid1;  
    38.     printf("main thread begins running. my_errno=%d\n",my_errno);  
    39.     pthread_key_create(&key, destr);  
    40.     pthread_create(&thid1, NULL, thread1, NULL);  
    41.     sleep(4);  
    42.     pthread_key_delete(key);   
    43.     printf("main thread exit\n");  
    44.     return 0;  
    45. }  
posted on 2014-10-26 08:35  知了112  阅读(200)  评论(0编辑  收藏  举报