Guest User

Untitled

a guest
Jan 13th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <semaphore.h>
  5.  
  6. #define NUM_THREADS 5
  7.  
  8. void *s_one(void*);
  9. void *s_two(void*);
  10. void *s_three(void*);
  11. void *s_four(void*);
  12. void *s_five(void*);
  13.  
  14. sem_t s2;
  15. sem_t s4;
  16. sem_t mainwait;
  17. sem_t s5;
  18.  
  19. int S;
  20. int A=1;
  21. int B=2;
  22. int C=3;
  23. int D=4;
  24.  
  25.  
  26. int main()
  27. {
  28. //pthread_t thread_id[NUM_THREADS];
  29. sem_init(&s2, 0, 1);
  30. sem_init(&s4, 0, 0);
  31. sem_init(&s5, 0, 1);
  32. sem_init(&mainwait, 0, 1);
  33.  
  34. pthread_t thread1;
  35. pthread_t thread2;
  36. pthread_t thread3;
  37. pthread_t thread4;
  38. pthread_t thread5;
  39.  
  40. pthread_create(thread1,NULL,s_one,NULL);
  41. pthread_create(thread2,NULL,s_two,NULL);
  42. pthread_create(thread3,NULL,s_three,NULL);
  43. pthread_create(thread4,NULL,s_four,NULL);
  44. pthread_create(thread5,NULL,s_five,NULL);
  45.  
  46. sem_wait(&mainwait);
  47.  
  48. return 0;
  49. }
  50.  
  51.  
  52. void *s_one(void* arg)
  53. {
  54. printf("s_one");
  55. A = B+C;
  56. sem_post(&s2);
  57. }
  58.  
  59. void *s_two(void* arg)
  60. {
  61. sem_wait(&s2);
  62. printf("s_two");
  63. C = B * D;
  64. sem_post(&s4);
  65. }
  66.  
  67. void *s_three(void* arg)
  68. {
  69. printf("s_three");
  70. S = 0;
  71. sem_post(&s4);
  72. }
  73.  
  74. void *s_four(void* arg)
  75. {
  76. sem_wait(&s4);
  77. int j;
  78. int X=0;
  79.  
  80. for(j=A; j<=100; j++)
  81. {
  82. X = j + 1;
  83. S = S + (X+1); //(X+1) can be replaced by j+1.
  84. }
  85. sem_post(&s5);
  86. }
  87.  
  88. void *s_five(void* arg)
  89. {
  90. sem_wait(&s5);
  91. if(S > 1000)
  92. C = C * 2;
  93. sem_post(&mainwait);
  94. }
Add Comment
Please, Sign In to add comment