Advertisement
Guest User

Untitled

a guest
May 20th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. #include <iostream>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #define ODCZYT 0
  5. #define ZAPIS 1
  6. #define WORKERS 10
  7. using namespace std;
  8.  
  9. int semaphore[2];
  10.  
  11. void LOCK()
  12. {
  13. int x;
  14. read(semaphore[ODCZYT],&x,sizeof(x));
  15.  
  16. }
  17.  
  18. void UNLOCK()
  19. {
  20. int x=0;
  21.  
  22. write(semaphore[ZAPIS],&x,sizeof(x));
  23. }
  24.  
  25. void UNLOCK_INIT()
  26. {
  27. int x=3;
  28. write(semaphore[ZAPIS],&x,3*sizeof(x));
  29. }
  30.  
  31. void worker(int id, int potok_k)
  32. {
  33. int x = 0,i,j;
  34. cout << "Worker " << id << " startuje" << endl;
  35. LOCK();
  36.  
  37. for(int i=0;i<7;i++)
  38. {
  39. cout << "[" << id << "]";
  40. fflush(stdout);
  41. sleep(1);
  42. }
  43.  
  44. UNLOCK();
  45. cout << "Worker " << id << " konczy" << endl;
  46. write(potok_k,&x,sizeof(x));
  47. }
  48.  
  49. int main()
  50. {
  51.  
  52. int potok_konczacy[2],i,x;
  53. pipe(potok_konczacy);
  54. pipe(semaphore);
  55. UNLOCK_INIT();
  56. for(int i=0;i<WORKERS;i++)
  57. {
  58. if(!fork())
  59. {
  60. worker(i,potok_konczacy[ZAPIS]);
  61. return 0;
  62. }
  63. }
  64.  
  65. for(int i=0;i<WORKERS;i++)
  66. {
  67. read(potok_konczacy[ODCZYT], &x, sizeof(x));
  68. }
  69.  
  70.  
  71. return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement