WinAPIMutex cpp определяет точку входа для консольного приложения incl

 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
// WinAPIMutex.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>
#include <time.h>
unsigned __stdcall write(void* lol);
unsigned __stdcall write2(void* lol);
unsigned __stdcall reader(void* lol);
HANDLE threads[3];
HANDLE hIn, hOut, Writer, Writer2, Reader;
DWORD thID1, thID2,count=10;
TCHAR bufIn[128] = { 0 }, *b = bufIn,i,c;
BOOL check=TRUE;
int _tmain(int argc, _TCHAR* argv[])
{
Writer = CreateMutex(NULL, FALSE, NULL);
Reader = CreateMutex(NULL, FALSE, NULL);
threads[0] =(HANDLE)_beginthreadex(NULL,NULL, &write, NULL,0,0);
threads[1] =(HANDLE)_beginthreadex(NULL, NULL, &write2, NULL, 0, 0);
threads[2] =(HANDLE)_beginthreadex(NULL, NULL, &reader, NULL, 0, 0);
while (check){
if (count == 0)check = FALSE;
};
//system("pause");
return 0;
}
unsigned __stdcall write(void* lol){
while (check){
WaitForSingleObject(Writer, INFINITE);
if (bufIn[0] == 0){
hIn = CreateFile(_T("in.txt"), GENERIC_ALL, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
srand(time(0)+rand());
int a = 1 + rand() % 9;
std::cout << "Writer1" << std::endl;
wsprintf(bufIn, L"%d", a);
WriteFile(hIn, b, 1, NULL, NULL);
}
ReleaseMutex(Writer);
}
return 0;
}
unsigned __stdcall write2(void* lol){
while (check){
WaitForSingleObject(Writer, INFINITE);
if (bufIn[0] == 0){
hIn = CreateFile(_T("in.txt"), GENERIC_ALL, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
srand(time(0)+rand());
int a = 1 + rand() % 10;
std::cout << "Writer2" << std::endl;
wsprintf(bufIn, L"%d", a);
WriteFile(hIn, b, 1, NULL, NULL);
}
ReleaseMutex(Writer);
}
return 0;
}
unsigned __stdcall reader(void* lol){
while (check){
WaitForSingleObject(Reader, INFINITE);
WaitForSingleObject(Writer, INFINITE);
if (bufIn[0]!=0){
ReleaseMutex(Writer);
hIn = CreateFile(_T("in.txt"), GENERIC_ALL, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
ReadFile(hIn, b, 1, NULL, NULL);
char* a = (char*)bufIn;
int res = atoi(a);
std::cout << res*5 << std::endl;
count--;
memset(bufIn, 0, 128);
//Sleep(1000);
}
ReleaseMutex(Reader);
}
return 0;
}