CriticalSections lab8 cpp Defines the entry point for the console appl

 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
// CriticalSections(lab8).cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<Windows.h>
#include<process.h>
#include<iostream>
#include<time.h>
HANDLE Read, Write,COut;
int count=0;
UINT WINAPI ThreadWrite1(LPVOID Param);
UINT WINAPI ThreadWrite2(LPVOID Param);
UINT WINAPI ThreadRead(LPVOID Param);
CRITICAL_SECTION CrSc;
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&CrSc);
HANDLE Thread1,Thread2,Thread3;
CreatePipe(&Read,&Write,NULL,0);
COut=GetStdHandle(STD_OUTPUT_HANDLE);
Thread1=(HANDLE)_beginthreadex(0,0,ThreadWrite1,NULL,0,NULL);
Thread2=(HANDLE)_beginthreadex(0,0,ThreadWrite2,NULL,0,NULL);
Thread3=(HANDLE)_beginthreadex(0,0,ThreadRead,NULL,0,NULL);
HANDLE Threads[]={Thread1, Thread2, Thread3};
WaitForMultipleObjects(3,Threads,TRUE,INFINITE);
return 0;
}
UINT WINAPI ThreadWrite1(LPVOID Param)
{
EnterCriticalSection(&CrSc);
srand(time(NULL));
DWORD num;
TCHAR digit[10]={0},Info[32]={0};
int x=0;
x=rand()%100+1;
WriteFile(Write,_itow(x,digit,10),sizeof(digit),&num,NULL);
_stprintf(Info,L"\nWriter1 writed: %d\n",x);
WriteConsole(COut,Info,_tcslen(Info),NULL,NULL);
count++;
LeaveCriticalSection(&CrSc);
return 0;
}
UINT WINAPI ThreadWrite2(LPVOID Param)
{
EnterCriticalSection(&CrSc);
srand(time(NULL));
DWORD num;
TCHAR digit[10]={0},Info[32]={0};
int x=0;
x=rand()%100-rand()%100;
WriteFile(Write,_itow(x,digit,10),sizeof(digit),&num,NULL);
_stprintf(Info,L"\nWriter2 writed: %d\n",x);
WriteConsole(COut,Info,_tcslen(Info),NULL,NULL);
count++;
LeaveCriticalSection(&CrSc);
return 0;
}
UINT WINAPI ThreadRead(LPVOID Param)
{
EnterCriticalSection(&CrSc);
DWORD num;
TCHAR digit[10]={0},Info[64]={0};
int i,x=0;
while(count){
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);
count--;
}
LeaveCriticalSection(&CrSc);
return 0;
}