condvar.pthread.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
  5. pthread_cond_t condvar = PTHREAD_COND_INITIALIZER;
  6. void* function1();
  7. void* function2();
  8. int count = 0;
  9. #define COUNT_DONE 10
  10. #define COUNT_HALT1 3
  11. #define COUNT_HALT2 6
  12. int main(int argc, const char** argv) {
  13. pthread_t thread1, thread2;
  14. pthread_create(&thread1, NULL, &function1, NULL);
  15. pthread_create(&thread2, NULL, &function2, NULL);
  16. pthread_join(thread1, NULL);
  17. pthread_join(thread2, NULL);
  18. printf("Final count: %d\n", count);
  19. return 0;
  20. }
  21. void* function1(void) {
  22. for (;;) {
  23. // Lock mutex and then wait for signal to relase mutex
  24. pthread_mutex_lock(&count_mutex);
  25. // Wait while functionCount2() operates on count
  26. // mutex unlocked if condition varialbe in functionCount2() signaled.
  27. pthread_cond_wait(&condvar, &count_mutex);
  28. count++;
  29. printf("Counter value in function1: %d\n", count);
  30. pthread_mutex_unlock(&count_mutex);
  31. if (count >= COUNT_DONE)
  32. return NULL;
  33. }
  34. }
  35. void* function2(void) {
  36. for (;;) {
  37. pthread_mutex_lock(&count_mutex);
  38. if (count < COUNT_HALT1 || count > COUNT_HALT2) {
  39. // Condition of if statement has been met.
  40. // Signal to free waiting thread by freeing the mutex.
  41. // Note: functionCount1() is now permitted to modify "count".
  42. pthread_cond_signal(&condvar);
  43. } else {
  44. count++;
  45. printf("Counter value function2: %d\n", count);
  46. }
  47. pthread_mutex_unlock(&count_mutex);
  48. if (count >= COUNT_DONE)
  49. return NULL;
  50. }
  51. }