#include #include #include #define MAX_BUF 256 using namespace std; int msgCount, pCount; // messages count, r/w count TCHAR buf[MAX_BUF] = {0}; HANDLE hMutexR1, hMutexR2, hMutexW1, hMutexW2; // mutex for maximum 2 current r/w HANDLE hMsgA, hMsgB; // msg events HANDLE hEndW, hEndR; // end session events bool getRaW(); bool getMSG(); int main() { if(!getRaW() || !getMSG()) // get r/w and messages { printf("Incorrect value!\r\n"); return 0; } //printf("MSG: %d\r\nRaW: %d\r\n", msgCount, pCount); hMutexR1 = CreateMutex(NULL, FALSE, L"MutexR1"); hMutexR2 = CreateMutex(NULL, FALSE, L"MutexR2"); hMutexW1 = CreateMutex(NULL, FALSE, L"MutexW1"); hMutexW2 = CreateMutex(NULL, FALSE, L"MutexW2"); hMsgA = CreateEvent(NULL, TRUE, FALSE, L"MessageA"); hMsgB = CreateEvent(NULL, TRUE, FALSE, L"MessageB"); hEndW = CreateEvent(NULL, TRUE, FALSE, L"EndW"); hEndR = CreateEvent(NULL, TRUE, FALSE, L"EndR"); StringCbPrintf(buf, MAX_BUF, L"%d", msgCount); // total msg per session SetEnvironmentVariable(L"msgCount", buf); int i = 0; while (i < pCount) // run r/w count { i++; STARTUPINFO si, si2; // some vars PROCESS_INFORMATION pi, pi2; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); ZeroMemory(&si2, sizeof(STARTUPINFO)); si2.cb = sizeof(STARTUPINFO); // start writer and reader if (!CreateProcess(L"Writer.exe", NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) // relative path { printf("Can't start Writer.exe\r\n"); return GetLastError(); } if (!CreateProcess(L"Reader.exe", NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si2, &pi2)) { printf("Can't start Reader.exe\r\n"); return GetLastError(); } } // open end session events int ends = 0; HANDLE hEnd[2]; hEnd[0] = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"EndW"); hEnd[1] = OpenEvent(EVENT_ALL_ACCESS, FALSE, L"EndR"); while (ends < pCount) // wait all sessions end { WaitForMultipleObjects(2, hEnd, TRUE, INFINITE); ResetEvent(hEnd[0]); // reset events for next session ResetEvent(hEnd[1]); ends++; printf("Writer and Reader session closed\r\n"); } printf("\r\nInput any char to exit...\r\n"); scanf_s("%d", &pCount); // close all handles CloseHandle(hMutexR1); CloseHandle(hMutexR2); CloseHandle(hMutexW1); CloseHandle(hMutexW2); CloseHandle(hMsgA); CloseHandle(hMsgB); CloseHandle(hEndW); CloseHandle(hEndR); return 0; } bool getRaW() { printf("Enter number of Readers/Writers (max 10): "); if (scanf_s("%d", &pCount) == 0) return false; if(pCount > 10) { pCount = 10; printf("Number of Readers/Writers set to 10 (max)\r\n"); } if(pCount < 1) { pCount = 1; printf("Number of Readers/Writers set to 1 (min)\r\n"); } return true; } bool getMSG() { printf("Enter number of messages (max 10): "); if (scanf_s("%d", &msgCount) == 0) return false; if(msgCount > 10) { msgCount = 10; printf("Number of messages set to 10 (max)\r\n"); } if(msgCount < 1) { msgCount = 1; printf("Number of messages set to 1 (min)\r\n"); } return true; }