pthread_key.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (C) 2023 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <pthread.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. pthread_key_t key;
  9. pthread_mutex_t lock;
  10. struct test_struct {
  11. int i;
  12. int k;
  13. };
  14. typedef struct point {
  15. int x;
  16. int y;
  17. } Point;
  18. void *
  19. child1(void *arg)
  20. {
  21. struct test_struct struct_data;
  22. struct_data.i = 10;
  23. struct_data.k = 5;
  24. pthread_mutex_lock(&lock);
  25. pthread_setspecific(key, &struct_data);
  26. printf("thread1--address of struct_data is --> %p\n", &(struct_data));
  27. printf("thread1--from pthread_getspecific(key) get the pointer and it "
  28. "points to --> %p\n",
  29. (struct test_struct *)pthread_getspecific(key));
  30. printf("thread1--from pthread_getspecific(key) get the pointer and print "
  31. "it's content:\nstruct_data.i:%d\nstruct_data.k: %d\n",
  32. ((struct test_struct *)pthread_getspecific(key))->i,
  33. ((struct test_struct *)pthread_getspecific(key))->k);
  34. printf("------------------------------------------------------\n");
  35. pthread_mutex_unlock(&lock);
  36. }
  37. void *
  38. child2(void *arg)
  39. {
  40. int temp = 20;
  41. pthread_mutex_lock(&lock);
  42. printf("thread2--temp's address is %p\n", &temp);
  43. pthread_setspecific(key, &temp);
  44. printf("thread2--from pthread_getspecific(key) get the pointer and it "
  45. "points to --> %p\n",
  46. (int *)pthread_getspecific(key));
  47. printf("thread2--from pthread_getspecific(key) get the pointer and print "
  48. "it's content --> temp:%d\n",
  49. *((int *)pthread_getspecific(key)));
  50. printf("------------------------------------------------------\n");
  51. pthread_mutex_unlock(&lock);
  52. }
  53. int
  54. main(void)
  55. {
  56. Point p;
  57. p.x = 10;
  58. p.y = 20;
  59. pthread_t tid1, tid2;
  60. pthread_mutex_init(&lock, NULL);
  61. pthread_key_create(&key, NULL);
  62. pthread_create(&tid1, NULL, child1, NULL);
  63. pthread_create(&tid2, NULL, child2, NULL);
  64. pthread_mutex_lock(&lock);
  65. printf("main--temp's address is %p\n", &p);
  66. pthread_setspecific(key, &p);
  67. printf("main--from pthread_getspecific(key) get the pointer and it points "
  68. "to --> %p\n",
  69. (int *)pthread_getspecific(key));
  70. printf("main--from pthread_getspecific(key) get the pointer and print "
  71. "it's content --> x:%d, y:%d\n",
  72. ((Point *)pthread_getspecific(key))->x,
  73. ((Point *)pthread_getspecific(key))->y);
  74. pthread_mutex_unlock(&lock);
  75. pthread_join(tid1, NULL);
  76. pthread_join(tid2, NULL);
  77. pthread_key_delete(key);
  78. return 0;
  79. }