Advertisement
zaxisss

Untitled

Jan 13th, 2021 (edited)
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <semaphore.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. sem_t s1, s2, s3;
  6. pthread_t thread1, thread2, thread3;
  7. void *thread_1();
  8. void *thread_2();
  9. void *thread_3();
  10.  
  11.  
  12. int main() {
  13. sem_init(&s1,0,1);
  14. sem_init(&s2,0,1);
  15. sem_init(&s3,0,1);
  16. pthread_create(&thread1, NULL, thread_1, NULL);
  17. pthread_create(&thread2, NULL, thread_2, NULL);
  18. pthread_create(&thread3, NULL, thread_3, NULL);
  19. pthread_join(thread1, NULL);
  20. pthread_join(thread2, NULL);
  21. pthread_join(thread3, NULL);
  22. printf("\n");
  23. }
  24.  
  25. void *thread_1(){
  26. for(int i=0; i<10;i++)
  27. {
  28. sem_wait(&s1);
  29. sleep(1);
  30. sem_wait(&s2);
  31. sleep(1);
  32. sem_wait(&s3);
  33. printf("\nOperacje na wspolnych danych watek 2 (%d)", i);
  34. sleep(1);
  35. sem_post(&s1);
  36. sem_post(&s2);
  37. sem_post(&s3);
  38. }
  39. }
  40.  
  41. void *thread_2(){
  42. for(int i=0; i<10;i++)
  43. {
  44. sem_wait(&s2);
  45. sleep(1);
  46. sem_wait(&s1);
  47. sleep(1);
  48. sem_wait(&s3);
  49. printf("\nOperacje na wspolnych danych watek 1 (%d)", i);
  50. sleep(1);
  51. sem_post(&s2);
  52. sem_post(&s1);
  53. sem_post(&s3);
  54. }
  55. }
  56.  
  57. void *thread_3(){
  58. for(int i=0; i<10;i++)
  59. {
  60. sem_wait(&s3);
  61. sleep(1);
  62. sem_wait(&s2);
  63. sleep(1);
  64. sem_wait(&s1);
  65. printf("\nOperacje na wspolnych danych watek 3 (%d)", i);
  66. sleep(1);
  67. sem_post(&s3);
  68. sem_post(&s2);
  69. sem_post(&s1);
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement