Advertisement
Guest User

Untitled

a guest
May 29th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4.  
  5. pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
  6. pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
  7.  
  8. void *function_count1();
  9. void *function_count2();
  10.  
  11. int count = 1;
  12.  
  13. int main()
  14. {
  15. pthread_t thread1, thread2;
  16. int ret;
  17.  
  18. /* Create independent threads each of which will execute function_count1 */
  19.  
  20. if( (ret=pthread_create( &thread1, NULL, &function_count1, "thread1")) )
  21. {
  22. printf("Thread 1 creation failed: %dn", ret);
  23. exit (EXIT_FAILURE);
  24. }
  25.  
  26. if( (ret=pthread_create( &thread2, NULL, &function_count2, "thread2")) )
  27. {
  28. printf("Thread 2 creation failed: %dn", ret);
  29. exit (EXIT_FAILURE);
  30. }
  31.  
  32. pthread_join( thread1, NULL);
  33. pthread_join( thread2, NULL);
  34.  
  35. exit(EXIT_SUCCESS);
  36. }
  37.  
  38. void *function_count1(void *arg)
  39. {
  40. while(count <= 10)
  41. {
  42. // lock mutex and then wait for signal to release mutex
  43. pthread_mutex_lock( &count_mutex );
  44. if (count % 2 != 0)
  45. {
  46. pthread_cond_wait(&condition_var, &count_mutex);
  47. printf("%s : counter = %dn", (char *)arg, count++);
  48. }
  49. else
  50. {
  51. pthread_cond_signal(&condition_var);
  52. }
  53. pthread_mutex_unlock( &count_mutex );
  54. }
  55. //return;
  56. }
  57.  
  58. void *function_count2(void *arg)
  59. {
  60. while(count <= 10)
  61. {
  62. pthread_mutex_lock( &count_mutex );
  63.  
  64. if (count % 2 == 0)
  65. {
  66. pthread_cond_wait(&condition_var, &count_mutex);
  67. printf("%s : counter = %dn", (char *)arg, count++);
  68. }
  69. else
  70. {
  71. pthread_cond_signal(&condition_var);
  72. }
  73. pthread_mutex_unlock(&count_mutex);
  74. }
  75. //return;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement