新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

[Linux线程]使用线程的私有数据-创新互联

#include 
#include 
#include 
#include 
#include 
#if 0    //预定义
char * str_accumulate(char *s)
{
    static char accu[1024]={0};
    strcat(accu,s);
    return accu;
}
#endif
  static pthread_key_t str_key;     //顶一个键值
  static pthread_once_t str_alloc_key_once = PTHREAD_ONCE_INIT;  //用于解决键冲突
  static void str_alloc_key();  //按键分配函数
  static void str_alloc_destroy_accu(void *accu);  //撤销按键分配函数
  //处理函数
  char * str_accumulate(const char *s)
  {
    char *accu;
    pthread_once(&str_alloc_key_once,str_alloc_key);  //解决按键冲突
    accu = (char *)pthread_getspecific(str_key);      //获取线程的私有数据地址
    if(accu == NULL)
    {
      accu = malloc(1024);   //分配1024的空间
      if(accu == NULL)  //如果accu为NULL则直接返回NULL
      {
        return NULL;
      }
      accu[0] = 0;
      pthread_setspecific(str_key,(void *)accu);   //将accu存放的数据作为键值关联
      printf("Thread %lx : allocating buffer at %p\n",pthread_self(),accu); //打印输出
    }
    strcat (accu,s);  //将accu和s字符串连接到一起
    return accu;
  }
  //这是一个键值分派函数
  static void str_alloc_key()
  {
    pthread_key_create(&str_key,str_alloc_destroy_accu);   //创建键值
    printf("Thread %lx : allocated key %d\n",pthread_self(), str_key);
  }
  //这是撤销键值的函数
  static void str_alloc_destroy_accu(void *accu)
  {
    printf("Thread %lx : freeing buffer at %p\n",pthread_self(),accu);
    free(accu);      //释放空间
  }
  //线程处理函数
  void *threaddeal(void *arg)
  {
    //该函数的主要工作是将arg的字符串和“Result of和thread连接到一起”
    char *str;
    str = str_accumulate("Result of ");
    str = str_accumulate((char *)arg);
    str = str_accumulate(" thread");
    printf("Thread %lx: \"%s\" \n",pthread_self(),str);
    return NULL;
  }
//主函数
int main(int argc, char *argv[])
{
  char *str;
  pthread_t th2,th3;
  str = str_accumulate("Result of ");
  pthread_create(&th2,NULL,threaddeal,(void *)"first");
  pthread_create(&th3,NULL,threaddeal,(void *)"second");  //建立两个线程
  str = str_accumulate("initial thread");
  printf("Thread %lx :\"%s\"\n",pthread_self(),str);
  pthread_join(th2,NULL);
  pthread_join(th3,NULL);   //阻塞线程1和线程2
  return 0;
}

创新互联是一家专注于网站设计制作、网站设计与策划设计,牙克石网站建设哪家好?创新互联做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:牙克石等地区。牙克石做网站价格咨询:13518219792

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


网站栏目:[Linux线程]使用线程的私有数据-创新互联
链接地址:http://www.wjwzjz.com/article/dhpssj.html
在线咨询
服务热线
服务热线:028-86922220
TOP