登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Code@Pig Home

喜欢背着一袋Code傻笑的Pig .. 忧美.欢笑.记忆.忘却 .之. 角落

 
 
 

日志

 
 

[pthread] thread-specific data  

2009-12-29 20:46:36|  分类: pthread |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
想使用 thread-specific data,首先要通过 pthread_key_create() 拿到一个 key。之后每个线程都可以使用此 key,但每个线程各自设置自己的 specific data (pthread_setspecific / getspecific),互不影响。

用 pthrad_key_delete() 释放此 key。key 的释放并不会调用 specific data destructor,destructor 会在线程退出时自动调用。

啥时候会用此种 thread-specific data 呢?
  1. 用来实现 errno

---------------------------------
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void mydtor(void *data)
{
        printf("dtor = %p\n", data);
        free(data);
}

void *mythr1(void *arg)
{
        char *data = malloc(10);
        pthread_key_t key = (pthread_key_t) arg;

        printf("thr #1 data1 = %p\n", data);
        pthread_setspecific(key, data);
        sleep(1);

        data = pthread_getspecific(key);
        printf("thr #1 data2 = %p\n", data);

        return (void *)0;
}

void *mythr2(void *arg)
{
        char *data = malloc(10);
        pthread_key_t key = (pthread_key_t) arg;

        sleep(1);
        printf("thr #2 data1 = %p\n", data);
        pthread_setspecific(key, data);

        data = pthread_getspecific(key);
        printf("thr #2 data2 = %p\n", data);

        return (void *)0;
}

int main()
{
        pthread_t pid1, pid2;
        pthread_key_t key;

        pthread_key_create(&key, mydtor);

        pthread_create(&pid1, NULL, mythr1, (void *)key);
        pthread_create(&pid2, NULL, mythr2, (void *)key);

        pthread_join(pid1, NULL);
        pthread_join(pid2, NULL);

        pthread_key_delete(key);
        return 0;
}
---------------------------------
$ ./a.out
thr #1 data1 = 0x804c3f0
thr #2 data1 = 0x804c400
thr #2 data2 = 0x804c400
dtor = 0x804c400
thr #1 data2 = 0x804c3f0
dtor = 0x804c3f0
---------------------------------


  评论这张
 
阅读(1334)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018