pthread_mutex.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. typedef struct ct_sum {
  9. int sum;
  10. pthread_mutex_t lock;
  11. } ct_sum;
  12. void *
  13. add1(void *cnt)
  14. {
  15. pthread_mutex_lock(&(((ct_sum *)cnt)->lock));
  16. printf("get lock thread1 id:%lu\n", pthread_self());
  17. int i;
  18. for (i = 0; i < 50; i++) {
  19. (*(ct_sum *)cnt).sum += i;
  20. }
  21. pthread_mutex_unlock(&(((ct_sum *)cnt)->lock));
  22. pthread_exit(NULL);
  23. return 0;
  24. }
  25. void *
  26. add2(void *cnt)
  27. {
  28. int i;
  29. cnt = (ct_sum *)cnt;
  30. pthread_mutex_lock(&(((ct_sum *)cnt)->lock));
  31. printf("get lock thread2 id:%lu\n", pthread_self());
  32. for (i = 50; i < 101; i++) {
  33. (*(ct_sum *)cnt).sum += i;
  34. }
  35. pthread_mutex_unlock(&(((ct_sum *)cnt)->lock));
  36. pthread_exit(NULL);
  37. return 0;
  38. }
  39. int
  40. main(void)
  41. {
  42. int i;
  43. pthread_t ptid1, ptid2;
  44. int sum = 0;
  45. ct_sum cnt;
  46. pthread_mutex_init(&(cnt.lock), NULL);
  47. cnt.sum = 0;
  48. pthread_create(&ptid1, NULL, add1, &cnt);
  49. pthread_create(&ptid2, NULL, add2, &cnt);
  50. pthread_join(ptid1, NULL);
  51. pthread_join(ptid2, NULL);
  52. pthread_mutex_lock(&(cnt.lock));
  53. printf("sum %d\n", cnt.sum);
  54. pthread_mutex_unlock(&(cnt.lock));
  55. pthread_mutex_destroy(&(cnt.lock));
  56. return 0;
  57. }