main.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <stdio.h>
  6. #include <pthread.h>
  7. #include <semaphore.h>
  8. static pthread_mutex_t mutex;
  9. static pthread_cond_t cond;
  10. static sem_t *sem;
  11. static void *
  12. thread(void *arg)
  13. {
  14. int *num = (int *)arg;
  15. pthread_mutex_lock(&mutex);
  16. printf("thread start \n");
  17. for (int i = 0; i < 10; i++) {
  18. *num = *num + 1;
  19. printf("num: %d\n", *num);
  20. }
  21. pthread_cond_signal(&cond);
  22. pthread_mutex_unlock(&mutex);
  23. sem_post(sem);
  24. printf("thread exit \n");
  25. return NULL;
  26. }
  27. int
  28. main(int argc, char *argv[])
  29. {
  30. pthread_t tid;
  31. int num = 0, ret = -1;
  32. if (pthread_mutex_init(&mutex, NULL) != 0) {
  33. printf("Failed to init mutex.\n");
  34. return -1;
  35. }
  36. if (pthread_cond_init(&cond, NULL) != 0) {
  37. printf("Failed to init cond.\n");
  38. goto fail1;
  39. }
  40. // O_CREAT and S_IRGRPS_IRGRP | S_IWGRP on linux (glibc), initial value is 0
  41. if (!(sem = sem_open("tessstsem", 0100, 0x10 | 0x20, 0))) {
  42. printf("Failed to open sem. %p\n", sem);
  43. goto fail2;
  44. }
  45. pthread_mutex_lock(&mutex);
  46. if (pthread_create(&tid, NULL, thread, &num) != 0) {
  47. printf("Failed to create thread.\n");
  48. pthread_mutex_unlock(&mutex);
  49. goto fail3;
  50. }
  51. printf("cond wait start\n");
  52. pthread_cond_wait(&cond, &mutex);
  53. pthread_mutex_unlock(&mutex);
  54. printf("cond wait success.\n");
  55. if (sem_wait(sem) != 0) {
  56. printf("Failed to wait sem.\n");
  57. }
  58. else {
  59. printf("sem wait success.\n");
  60. }
  61. if (pthread_join(tid, NULL) != 0) {
  62. printf("Failed to join thread.\n");
  63. }
  64. ret = 0;
  65. fail3:
  66. sem_close(sem);
  67. sem_unlink("tessstsem");
  68. fail2:
  69. pthread_cond_destroy(&cond);
  70. fail1:
  71. pthread_mutex_destroy(&mutex);
  72. return ret;
  73. }