condvar.pthread.c 1.6 KB

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