Advertisement
zaxisss

Untitled

Dec 16th, 2020 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 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. pthread_create(&thread1, NULL, thread_1, NULL);
  16. pthread_create(&thread2, NULL, thread_2, NULL);
  17. pthread_join(thread1, NULL);
  18. pthread_join(thread2, NULL);
  19. printf("\n");
  20. }
  21.  
  22. void *thread_1(){
  23. for(int i=0; i<10;i++)
  24. {
  25. sem_wait(&s1);
  26. sleep(1);
  27. sem_wait(&s2);
  28. printf("\nOperacje na wspolnych danych watek 2 (%d)", i);
  29. sleep(1);
  30. sem_post(&s1);
  31. sem_post(&s2);
  32. }
  33. }
  34.  
  35. void *thread_2(){
  36. for(int i=0; i<10;i++)
  37. {
  38. sem_wait(&s1);
  39. sleep(1);
  40. sem_wait(&s2);
  41. printf("\nOperacje na wspolnych danych watek 1 (%d)", i);
  42. sleep(1);
  43. sem_post(&s1);
  44. sem_post(&s2);
  45. }
  46. }
  47.  
  48. void *thread_3(){
  49. for(int i=0; i<10;i++)
  50. {
  51. sem_wait(&s1);
  52. sleep(1);
  53. sem_wait(&s2);
  54. printf("\nOperacje na wspolnych danych watek 3 (%d)", i);
  55. sleep(1);
  56. sem_post(&s1);
  57. sem_post(&s2);
  58. }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement