The problem of cannibals. When the savage wants to eat, he eats 1 piece out of the pot, unless the pot is empty, otherwise the savage wakes the cook and waits until he fills the pot. The cook, having cooked dinner, falls asleep. Create a multi-threaded application that simulates a savage lunch. When solving the problem of using semaphores. On the screen you need to display the status of each of the n savages (eats or waits), the state of the cook (asleep or cooks). message about the fullness of the pot (full or empty).
#include <iostream> #include <stdio.h> #include <windows.h> #include <process.h> #include <stdlib.h> #include <Tchar.h> int n = 5; // ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΊΡΡΠΊΠΎΠ² - Π½ΠΎΡΠΌΠ° const int m = 1, // ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΏΡΠΎΠΈΠ·Π²ΠΎΠ΄ΠΈΡΠ΅Π»Π΅ΠΉ k = 10; // ΠΊΠΎΠ»ΠΈΡΠ΅ΡΡΠ²ΠΎ ΠΏΠΎΡΡΠ΅Π±ΠΈΡΠ΅Π»Π΅ΠΉ HANDLE hMutex; DWORD WINAPI Povar(void * arg) { int num = 0; num = *((int *)arg); while (1) { WaitForSingleObject(hMutex, INFINITE); printf(" I'm Povar :) "); if (n == 0) { printf(" Povar cooking \n"); n = 5; printf("povar sdelal %d kuskov meat\n", n); } printf(" now gorshok have some meat, that i can go to sleep \n"); Sleep(1000); ReleaseMutex(hMutex); Sleep(1000); } return 0; }; DWORD WINAPI Kanibal(void * arg) { int num = 0; num = *((int *)arg); while (1) { WaitForSingleObject(hMutex, INFINITE); printf(" Kanibal %d very want to eat!!!!! :) \n", num); if (n == 0) { printf(" kanibal ne kushaet, gorshok is empty \n "); Sleep(1000); } else { printf(" kanibal nomer %d kushaet kusok myasa = %d\n", num, n); n--; return 0; } ReleaseMutex(hMutex); Sleep(1000); } return 0; }; int main(int argc, char* argv) { DWORD dwThreadId[k + m]; HANDLE hThread[k + m]; hMutex = CreateMutex(NULL, FALSE, _T("MyMutex")); for (int j = 0; j < m; j++) { hThread[j] = CreateThread(NULL, 0, &Povar, 0, 0, &dwThreadId[j]); } for (int i = m; i < k + m; i++) { hThread[i] = CreateThread(NULL, 0, &Kanibal, 0, 0, &dwThreadId[i]); } WaitForMultipleObjects(11, hThread, TRUE, INFINITE); return 0; } 