condvar.pthread.c 1.9 KB

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