main.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. static pthread_mutex_t mutex;
  8. static pthread_cond_t cond;
  9. static void *thread(void *arg)
  10. {
  11. int *num = (int *)arg;
  12. pthread_mutex_lock(&mutex);
  13. printf("thread start \n");
  14. for (int i = 0; i < 10; i++) {
  15. *num = *num + 1;
  16. printf("num: %d\n", *num);
  17. }
  18. pthread_cond_signal(&cond);
  19. pthread_mutex_unlock(&mutex);
  20. printf("thread exit \n");
  21. return NULL;
  22. }
  23. int main(int argc, char *argv[])
  24. {
  25. pthread_t tid;
  26. int num = 0, ret = -1;
  27. if (pthread_mutex_init(&mutex, NULL) != 0) {
  28. printf("Failed to init mutex.\n");
  29. return -1;
  30. }
  31. if (pthread_cond_init(&cond, NULL) != 0) {
  32. printf("Failed to init cond.\n");
  33. goto fail1;
  34. }
  35. pthread_mutex_lock(&mutex);
  36. if (pthread_create(&tid, NULL, thread, &num) != 0) {
  37. printf("Failed to create thread.\n");
  38. goto fail2;
  39. }
  40. printf("cond wait start\n");
  41. pthread_cond_wait(&cond, &mutex);
  42. pthread_mutex_unlock(&mutex);
  43. printf("cond wait success.\n");
  44. if (pthread_join(tid, NULL) != 0) {
  45. printf("Failed to join thread.\n");
  46. }
  47. ret = 0;
  48. fail2:
  49. pthread_cond_destroy(&cond);
  50. fail1:
  51. pthread_mutex_destroy(&mutex);
  52. return ret;
  53. }