main.c 1.4 KB

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