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

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

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

24. 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);

25.

26. printf ("------------------------------------------------------n");

27.}

28.

29.void *child2 (void *arg)

30.{

31. int temp = 20;

32. sleep (2);

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

34. pthread_setspecific (key, &temp);

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

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

37.}

38.

39.int main (void)

40.{

41. pthread_t tid1, tid2;

42.

43. pthread_key_create (&key, NULL);

44.

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

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

47. pthread_join (tid1, NULL);

48. pthread_join (tid2, NULL);

49.

50. pthread_key_delete (key);

51.

52. return (0);

53.}

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

pthread_key_t key;

struct test_struct {

int i;

float k;

};

void *child1 (void *arg)

{

struct test_struct struct_data;

struct_data.i = 10;

struct_data.k = 3.1415;

pthread_setspecific (key, &struct_data);

printf ("结构体struct_data的地址为 0x%pn", &(struct_data));

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

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

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

推荐文章
    热点阅读