UNIX情形高级编程:线程私稀有据
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)); (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |