您的位置:首页 > 其它

线程特定数据函数的使用

2013-01-08 19:31 323 查看
《APUE》 12.6节

线程特定数据(或线程私有数据,TSD) 的学习

建议参考《unix网络编程卷1》的第26.5节来看,它讲得更加详细。

练习代码如下:

#include "apue.h"
#include <pthread.h>

static pthread_key_t r_key;
static pthread_once_t  r_once = PTHREAD_ONCE_INIT;

void  free_buf(void * buf)
{
free(buf);
}

void key_init(void)
{
pthread_key_create(&r_key,free_buf);
}

void * operation(void * thread_num)
{
int  num = (int)thread_num;
pthread_detach(pthread_self());
pthread_once(&r_once,key_init);
int * data;

if(pthread_getspecific(r_key) == NULL)
{
printf("malloc:\n");
data = (int *)malloc(sizeof(int));
pthread_setspecific(r_key,data);
*data = num;
}

printf("the specific data of Thread %d is %d\n",num, *((int *)pthread_getspecific(r_key)));

if(num == 1234)
{
sleep(5);// 让5678进程能够执行到sleep 10s
pthread_key_delete(r_key);
}else
{   // 让1234进程能够执行到sleep 5,delete key
sleep(10);
}

if(pthread_getspecific(r_key) != NULL)
{
printf("-----the specific data of Thread %d is %d\n",num,
*((int *)pthread_getspecific(r_key)));
}else
{
printf("---- the Thread num is %d, and it  have no specific data \n",num);
}

pthread_exit(NULL);

return((void *)0);
}

int main()
{

pthread_t tid1,tid2;
int err = 0;

err = pthread_create(&tid1,NULL,operation,(void *)1234);
if(err != 0)
{
printf("can not crate thread 1\n");
return -1;
}

err = pthread_create(&tid2,NULL,operation,(void *)5678);
if(err != 0)
{
printf("can not crate thread 2\n");
return -1;
}

sleep(20);//等待线程打印结果

return 0;

}


可以看到在thread 1234执行了pthread_key_delete()之后,不仅切断了thread 1234与其线程特定数据之间的联系,而且也切断了thread 5678与其线程特定数据之间的联系。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐