Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.31 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <fcntl.h>
  3. #include <string.h>
  4. #include <sys/mman.h>
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <pthread.h>
  8. #include <semaphore.h>
  9. #include <iostream>
  10. #include <cstdio>
  11. #include <atomic>
  12. #include <cstdio>
  13. #include <locale>
  14. #include <iomanip>
  15. #include <atomic>
  16. using namespace std;
  17.  
  18.  
  19. #define CUT_MIN_TIME 2
  20. #define CUT_MAX_TIME 5
  21.  
  22. #define COME_MIN_TIME 1
  23. #define COME_MAX_TIME 3
  24.  
  25. #define sh_mem "sm" // имя объекта разделяемой памяти
  26.  
  27.  
  28. struct Barbershop
  29. {
  30. sem_t customers; // в этом семафоре храним число ожидающих посетителей
  31. sem_t barbers; // семафор брадобрея
  32.  
  33. int waiting;
  34. int chair_count; // количество свободных стульев
  35. int customer_count; // количество посетителей в день
  36. int serviced_customer_count; // количество обслуженных посетителей
  37. atomic_int _end; //перемнная, операции увеличения(уменьшения) над которой будт неделимы для всех потоков
  38. };
  39.  
  40. //объект струткуры
  41. Barbershop* barbershop;
  42.  
  43. int come_time; // время прибытия посетителя
  44.  
  45.  
  46. void show_message(int threadid, char* person, char* msg, int w = 0)
  47. {
  48. cout.fill('.');
  49. cout << '[' << person << setw(w) << " " << threadid << "] " << msg << " " <<endl;
  50. }
  51.  
  52.  
  53. int barber()
  54. {
  55. while(barbershop->_end != -1)
  56. {
  57. // если значение семофора <0, то он блокируется, пока один из потоков не вызовет post
  58. sem_wait(&barbershop->customers); // ждем посетителей
  59. barbershop->waiting--;
  60. int cut_time = rand() % (CUT_MAX_TIME - CUT_MIN_TIME) + CUT_MIN_TIME;
  61. show_message(cut_time, (char*)"БРАДОБРЕЙ", (char*)"бреет бороду клиенту", 7);
  62. sleep(cut_time); // обслуживаем посетителя
  63. //Эта функция увеличивает значение семафора и разблокирует ожидающие потоки
  64. sem_post(&barbershop->barbers); // просыпаемся
  65. barbershop->serviced_customer_count++;
  66. }
  67. return 0;
  68. }
  69.  
  70.  
  71. int customer(int id)
  72. {
  73. barbershop->_end++;
  74. show_message(id, (char*)"КЛИЕНТ", (char*)"пришел.", 10);
  75. if(barbershop->waiting < barbershop->chair_count) // посетитель уходит если нет свободных мест
  76. {
  77. barbershop->waiting++;
  78. cout << "Ждущих посетителей: " << barbershop->waiting << endl;
  79. show_message(id, (char*)"КЛИЕНТ", (char*)"ждет.", 10);
  80. sem_post(&barbershop->customers);
  81. sem_wait(&barbershop->barbers); // ждем когда брадобрей освободится
  82. show_message(id, (char*)"КЛИЕНТ", (char*)"уходит довольным", 10);
  83. }
  84. else
  85. {
  86. show_message(id, (char*)"КЛИЕНТ", (char*)"ушел небритым.", 10);
  87. }
  88. barbershop->_end--;
  89. return 0;
  90. }
  91.  
  92. int main(int argc, char *argv[])
  93. {
  94. setlocale(LC_ALL, "Russian");
  95.  
  96. shm_unlink(sh_mem);
  97.  
  98. // создание/открытие объекта разделяемой памяти
  99. int fd = shm_open(sh_mem, O_RDWR | O_CREAT, 0777);
  100.  
  101. // отображение разделяемой памяти
  102. barbershop = (Barbershop*) mmap(0, sizeof(Barbershop), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  103.  
  104. ftruncate(fd, sizeof(Barbershop*));
  105.  
  106. // обнуляем всю разделяемую память
  107. memset((void*)barbershop, 0, sizeof(Barbershop));
  108. barbershop->customer_count = atoi(argv[1]);
  109. barbershop->chair_count = atoi(argv[2]);
  110. sem_init(&barbershop->customers, 1, 0);
  111. sem_init(&barbershop->barbers, 1, 0);
  112.  
  113. if (fork()>0)
  114. return barber();
  115.  
  116. for (int i = 0; i < barbershop->customer_count; ++i)
  117. {
  118. come_time = rand() % (COME_MAX_TIME - COME_MIN_TIME) + COME_MIN_TIME;
  119. sleep(come_time);
  120. if (fork()>0)
  121. return customer(i+1);
  122. }
  123.  
  124. while(barbershop->_end);
  125.  
  126. barbershop->_end = -1;
  127.  
  128. cout << "--------- Статистика рабочего дня -----------" << endl;
  129.  
  130. cout << "Количество побритых клиентов: " << barbershop->serviced_customer_count << endl;
  131.  
  132. shm_unlink(sh_mem);
  133.  
  134. return 0;
  135. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement