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...
      ");
      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
      ",(char*)arg,value);
      39 
      40     value = pthread_getspecific(key_tsd);
      41     printf("tid=0x%x str=%s
      ",value->tid,value->str);
      42     sleep(2);
      43 
      44     value = pthread_getspecific(key_tsd);
      45     printf("tid=0x%x str=%s
      ",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 }
    • 分析

      • 线程特定数据对每个线程都有一个独立的数据
作者:长风 Email:844064492@qq.com QQ群:607717453 Git:https://github.com/zhaohu19910409Dz 开源项目:https://github.com/OriginMEK/MEK 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利. 感谢您的阅读。如果觉得有用的就请各位大神高抬贵手“推荐一下”吧!你的精神支持是博主强大的写作动力。 如果觉得我的博客有意思,欢迎点击首页左上角的“+加关注”按钮关注我!
原文地址:https://www.cnblogs.com/zhaohu/p/9033276.html