加入收藏 | 设为首页 | 会员中心 | 我要投稿 应用网_丽江站长网 (http://www.0888zz.com/)- 科技、建站、数据工具、云上网络、机器学习!
当前位置: 首页 > 服务器 > 搭建环境 > Unix > 正文

UNIX环境高级编程:线程私有数据

发布时间:2016-09-27 17:04:36 所属栏目:Unix 来源:站长网
导读:副标题#e# 线程私有数据(Thread-specific data,TSD):存储和查询与某个线程相关数据的一种机制。 在进程内的所有线程都共享相同的地址空间,即意味着任何声明为静态或外部变量,或在进程堆声明的变量,都可以被进程内所有的线程读写。 一个线程真正拥有的

printf ("利用 pthread_getspecific(key)打印 child1 线程中与key关联的结构体中成员值:nstruct_data.i:%dnstruct_data.k: %fn", ((struct test_struct *)pthread_getspecific (key))->i, ((struct test_struct *)pthread_getspecific(key))->k);

printf ("------------------------------------------------------n");

}

void *child2 (void *arg)

{

int temp = 20;

sleep (2);

printf ("child2 中变量 temp 的地址为 0x%pn", &temp);

pthread_setspecific (key, &temp);

printf ("child2 中 pthread_getspecific(key)返回的指针为:0x%pn", (int *)pthread_getspecific(key));

printf ("利用 pthread_getspecific(key)打印 child2 线程中与key关联的整型变量temp 值:%dn", *((int *)pthread_getspecific(key)));

}

int main (void)

{

pthread_t tid1, tid2;

pthread_key_create (&key, NULL);

pthread_create (&tid1, NULL, (void *)child1, NULL);

pthread_create (&tid2, NULL, (void *)child2, NULL);

pthread_join (tid1, NULL);

pthread_join (tid2, NULL);

pthread_key_delete (key);

return (0);

}

运行结果:

[cpp] view plaincopyprint

01.huangcheng@ubuntu:~$ ./a.out

02.结构体struct_data的地址为 0x0xb77db388

03.child1 中 pthread_getspecific(key)返回的指针为:0x0xb77db388

04.利用 pthread_getspecific(key)打印 child1 线程中与key关联的结构体中成员值:

05.struct_data.i:10

06.struct_data.k: 3.141500

07.------------------------------------------------------

08.child2 中变量 temp 的地址为 0x0xb6fda38c

09.child2 中 pthread_getspecific(key)返回的指针为:0x0xb6fda38c

10.利用 pthread_getspecific(key)打印 child2 线程中与key关联的整型变量temp 值:20

(编辑:应用网_丽江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读