pthread线程特定数据

  • 举个栗子
    •  1 #include <stdio.h>
       2 #include <stdlib.h>
       3 #include <unistd.h>
       4 #include <sys/types.h>
       5 #include <pthread.h>
       6 #include <errno.h>
       7 #include <string.h>
       8 
       9 #define ERR_EXIT(m)\
      10     do\
      11     {\
      12         perror(m);\
      13         exit(EXIT_FAILURE);\
      14     }while(0)\
      15 
      16 typedef struct tsd
      17 {
      18     pthread_t tid;
      19     char* str;
      20 }tsd_t;
      21 
      22 pthread_key_t key_tsd;
      23 
      24 void destroy_routine(void* value)
      25 {
      26     free(value);
      27     printf("destroy...\n");
      28 }
      29 
      30 void* thread_routinne(void* arg)
      31 {
      32     tsd_t* value = (tsd_t*)malloc(sizeof(tsd_t));
      33     value->tid = pthread_self();
      34     value->str = (char*)arg;
      35 
      36     pthread_setspecific(key_tsd,value);
      37     
      38     printf("%s setspecific %p\n",(char*)arg,value);
      39 
      40     value = pthread_getspecific(key_tsd);
      41     printf("tid=0x%x str=%s\n",value->tid,value->str);
      42     sleep(2);
      43 
      44     value = pthread_getspecific(key_tsd);
      45     printf("tid=0x%x str=%s\n",value->tid,value->str);
      46     return NULL;
      47 }
      48 
      49 int main(void)
      50 {
      51     pthread_key_create(&key_tsd,destroy_routine);
      52     
      53     pthread_t tid1;
      54     pthread_t tid2;
      55     pthread_create(&tid1, NULL, thread_routinne, "thread1");
      56     pthread_create(&tid2, NULL, thread_routinne, "thread1");
      57 
      58     pthread_join(tid1,NULL);
      59     pthread_join(tid2,NULL);
      60 
      61     pthread_key_delete(key_tsd);
      62 
      63 
      64     return 0;
      65 }
    • 分析

      • 线程特定数据对每个线程都有一个独立的数据

猜你喜欢

转载自www.cnblogs.com/zhaohu/p/9033276.html