MutexesMFC lab5 cpp Defines the entry point for the console applicatio

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// MutexesMFC(lab5).cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "afxmt.h"
#include "MutexesMFC(lab5).h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define THREADS_WRITERS 2
// The one and only application object
CWinApp theApp;
CMutex Mutex;
HANDLE Read,Write,COut,Threads[THREADS_WRITERS];
int count1=0,n=0;
UINT Writer(LPVOID param);
UINT Reader(LPVOID param);
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.
COut=GetStdHandle(STD_OUTPUT_HANDLE);
CreatePipe(&Read,&Write,NULL,0);
for(n=1;n<=THREADS_WRITERS;n++)
{
Threads[n]=AfxBeginThread(Writer,(LPVOID)n);
}
AfxBeginThread(Reader,NULL);
WaitForSingleObject((HANDLE)*AfxBeginThread(Reader,NULL),10);
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
UINT Writer(LPVOID Param)
{
srand(time(NULL));
DWORD num;
TCHAR digit[10]={0},Info[32]={0};
int i=(int)Param,x=0,repeat=5;
while(repeat){
Mutex.Unlock();
x=rand()%100;
WriteFile(Write,_itow(x,digit,10),sizeof(digit),&num,NULL);
_stprintf(Info,L"\nWriter%d writed: %d\n",i,x);
WriteConsole(COut,Info,_tcslen(Info),NULL,NULL);
count1++;
repeat--;
Mutex.Lock();
}
return 0;
}
UINT Reader(LPVOID Param)
{
DWORD num;
TCHAR digit[10]={0},Info[64]={0};
int x=0,repeat=5;
BOOL rd=FALSE;
while(repeat){
Mutex.Unlock();
while(count1){
rd=ReadFile(Read,digit,sizeof(digit),&num,NULL);
x=_wtoi(digit);x*=10;
_stprintf(Info,L"\nRecieved digit was multiplied on 10: %d\n",x);
WriteConsole(COut,Info,_tcslen(Info),NULL,NULL);
if (rd!=FALSE){
count1--;rd=FALSE;
}
}
repeat--;
Mutex.Lock();
}
return 0;
}