多线程变量   pthread_key_t 自查文档

12 篇文章 0 订阅

相关接口:

#include <pthread.h>
// init_routine函数在多线程环境中只执行一次
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void));
pthread_once_t once_control = PTHREAD_ONCE_INIT;
 //新建 key,一个key只能执行一次. destructor为删除key释放处理函数。如果为空采用系统默认方式
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
int pthread_key_delete(pthread_key_t key);

void *pthread_getspecific(pthread_key_t key);
int pthread_setspecific(pthread_key_t key, const void *value);

eg:\

#include    <pthread.h>  
#include    <stdio.h>  
#include    <unistd.h>  
#include    <stdlib.h> //atexit

using  namespace  std;  

pthread_key_t  key;  
pthread_once_t thread_once = PTHREAD_ONCE_INIT;

void echomsg(void *);
void once_run(void)
{
    printf("pthread_key_t init in the once_run\n  ");
    pthread_key_create(&key,echomsg);

}
void  echomsg(void*  p)  
{  
    int  t=*(int*)p;  
    printf(  "destructor  excuted  in  thread  %d,  param=%d\n  ",pthread_self(),t);  
    delete (int *)p;
}  

void*  child1(void*  arg)  
{  
    int*ptid=  new  int;  

    pthread_once(&thread_once, once_run);//测试pthread_once是否还会在此执行不,因为在main线程已经执行了.
    *ptid=pthread_self();  
    printf(  "thread1  %d  enter\n  ",*ptid);  
    pthread_setspecific(key,(void*)ptid);  
    sleep(2);  
    printf(  "thread1  %d  returns  %d\n  ",*ptid,*((int*)pthread_getspecific(key)));  
    sleep(5);  
    pthread_exit(NULL);  
    return  NULL;  
}  

void*  child2(void*  arg)  
{  
    int*ptid=  new  int;  
    *ptid=pthread_self();  
    printf(  "thread2  %d  enter\n  ",*ptid);  
    pthread_setspecific(key,(void*)ptid);  
    sleep(1);  
    printf(  "thread2  %d  returns  %d\n  ",*ptid,*((int*)pthread_getspecific(key)));  
    sleep(1);  
    pthread_exit(NULL);  
    return  NULL;  
}  

void main_exit()
{
    pthread_key_delete(key);

}
int  main()  
{  
    pthread_t  tid1,tid2;  
    printf(  "hello\n  ");  
    atexit(main_exit);//为了防止sleep(4)放到pthread_key_delete(key)后面就会出现段错误了。但是个人也不很提倡用atexit这个函数。
    pthread_once(&thread_once, once_run);
    //pthread_key_create(&key,echomsg);  //保证一次性运行把其放到了pthread_once了
    pthread_create(&tid1,NULL,child1,NULL);  
    pthread_create(&tid2,NULL,child2,NULL);  
    //pthread_join(tid1,NULL);  
    //pthread_join(tid2,NULL);  
    sleep(10);  
    //pthread_key_delete(key);  
    printf(  "main  thread  %d  exit\n  ",pthread_self());  

    return  0;  
} 

http://blog.csdn.net/denny_233/article/details/7221831
http://blog.csdn.net/xqs83/article/details/8161753

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值