// Mutex.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Mutex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif UINT _cdecl Writer(LPVOID); UINT _cdecl Reader(LPVOID); void Write(void); void Read(void); CMutex mutex; CFile file; // The one and only application object CWinApp theApp; using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; HMODULE hModule = ::GetModuleHandle(NULL); if (hModule != NULL) { // initialize MFC and print and error on failure if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { // TODO: code your application's behavior here. CFileException FileException; while (TRUE) { if (!file.Open(_T("mutex.txt"), CFile::modeCreate | CFile::modeWrite, NULL, &FileException)) std::cout << "Erorr of creating file " << FileException.m_cause << std::endl; else { CWinThread* thread1 = AfxBeginThread(&Writer, NULL); CWinThread* thread2 = AfxBeginThread(&Writer, NULL); CWinThread* thread3 = AfxBeginThread(&Reader, NULL); HANDLE threadArray[3]; threadArray[0] = thread1->m_hThread; threadArray[1] = thread2->m_hThread; threadArray[2] = thread3->m_hThread; ::WaitForMultipleObjects(3, threadArray, TRUE, INFINITE); file.Close(); } } } } else { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: GetModuleHandle failed\n")); nRetCode = 1; } return nRetCode; } UINT _cdecl Writer(LPVOID param) { while (TRUE) { CSingleLock SyncObject(&mutex); if (!SyncObject.IsLocked()) { if (SyncObject.Lock(INFINITE)) { Write(); SyncObject.Unlock(); return 0; } } } return 0; } UINT _cdecl Reader(LPVOID param) { while (TRUE) { CSingleLock SyncObject(&mutex); if (!SyncObject.IsLocked()) { if (SyncObject.Lock(INFINITE)) { CFileException FileException; file.Close(); if (file.Open(_T("mutex.txt"), CFile::modeRead, NULL, &FileException)) { Read(); SyncObject.Unlock(); return 0; } else std::cout << "Error " << FileException.m_cause << std::endl; } } } return 0; } void Write(void) { srand((unsigned)time(NULL)); char buffer[256] = {0}; _itoa_s(rand()%100 + 1, buffer, sizeof(char)*256, 10); file.Write(buffer, strlen(buffer)); std::cout << "Write: " << buffer << std::endl; } void Read(void) { char buffer[256] = {0}; file.Read(buffer, 256); std::cout << "Read: " << buffer << std::endl; std::cout << "Result: " << atoi(buffer)*5 << std::endl; }