zoukankan      html  css  js  c++  java
  • 为线程特定数据创建键

    #include <stdlib.h>
    #include <pthread.h>
    #include <stdio.h>
    #include <sched.h>
    #include<string.h>
    pthread_key_t key;
    void destructor(void *data)
    //如果创建该键时指定了destructor 函数,则该线程终止时,系统会调用destructor 函数,传进的参数是绑定的值。
     {
           if(data != NULL)
              free(data);
            printf("thread (%u) do free key
    ", (unsigned)pthread_self());
    }
     void print_key(void)
     {
            char *p;
            p = (char *)pthread_getspecific(key);
            printf("(%u) key_value:%s
    ", (unsigned)pthread_self(), p);
     }
      void *thread1(void *arg)
     {
             printf("start thread (%u)
    ", (unsigned)pthread_self());
             char * p = malloc(7*sizeof(char));
             memset(p, 'a', 6);
             p[6] = '';
             pthread_setspecific(key, p);//key绑定的值为p
             printf("(%lu)setkey:%s
    ", pthread_self(), p);
             print_key();
             printf("thread (%u) end
    ", pthread_self());
     }
     void *thread2(void *arg)
     {
             printf("start thread (%u)
    ", (unsigned)pthread_self());
             char * p = malloc(7*sizeof(char));
             memset(p, 'c', 6);
             p[6] = '';
             pthread_setspecific(key, p);//key绑定的值为p
             printf("(%lu)setkey:%s
    ", pthread_self(), p);
             print_key();
             printf("thread (%u) end
    ", pthread_self());
     }
     int main(int argc, char *argv[])
     {
             pthread_t  t1, t2, t3;
     
             pthread_key_create(&key, destructor);
    
            pthread_create(&t1, NULL, thread1, NULL);
            pthread_create(&t2, NULL, thread2, NULL);
    
            pthread_join(t1, NULL);
            pthread_join(t2, NULL);
            printf("main end
    ");
          return 0;
     }
    //执行结果如下
    
    1.在每个线程结束后系统会执行注册的撤销函数。
    2.如果使用pthread_exit()提前终止线程,也会调用撤销函数。
  • 相关阅读:
    狡猾的商人
    差分约束系统
    【模板】负环
    关于Java8的精心总结
    rabbitmq+sleuth+zinkip 分布式链路追踪
    Linux下一只五颜六色的「猫」
    整理 Linux下列出目录内容的命令
    从封装变化的角度看设计模式——组件协作
    从封装变化的角度看设计模式——接口隔离
    从封装变化的角度看设计模式——对象创建
  • 原文地址:https://www.cnblogs.com/leijiangtao/p/4685609.html
Copyright © 2011-2022 走看看