// Critical Section.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Critical Section.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
UINT _cdecl Writer(LPVOID);
UINT _cdecl Reader(LPVOID);
void Write(void);
void Read(void);
CCriticalSection cs;
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("cs.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)
{
srand((unsigned)GetTickCount());
CSingleLock SyncObject(&cs);
if (!SyncObject.IsLocked())
{
if (SyncObject.Lock(INFINITE))
{
Write();
SyncObject.Unlock();
}
}
return 0;
}
UINT _cdecl
Reader(LPVOID param)
{
CSingleLock SyncObject(&cs);
if (!SyncObject.IsLocked())
{
if (SyncObject.Lock(INFINITE))
{
CFileException FileException;
file.Close();
if (file.Open(_T("cs.txt"), CFile::modeRead, NULL, &FileException))
{
Read();
SyncObject.Unlock();
}
else
std::cout << "Error " << FileException.m_cause << std::endl;
}
}
return 0;
}
void
Write(void)
{
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};
while(!file.Read(buffer, 256));
std::cout << "Read: " << buffer << std::endl;
std::cout << "Result: " << atoi(buffer)*5 << std::endl;
}