您的位置:首页 > 其它

多线程变量   pthread_key_t 自查文档

2016-05-19 16:29 344 查看
相关接口:

#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;
}


/article/8304809.html

/article/10629330.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: