condvar.pthread.c 1.8 KB

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