include stdafx include iostream include Windows include process includ

 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
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>
#include <locale>
void ThreadWriter1(void *ptr);
void ThreadWriter2(void *ptr);
void ThreadReader(void *ptr);
HANDLE hRead, hMutex, hWriter1, hWriter2, pipeRead, pipeWrite;
CRITICAL_SECTION cs;
uintptr_t Threads[3];
int count = 35;
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "Russian");
InitializeCriticalSection(&cs);
CreatePipe(&pipeRead,&pipeWrite,NULL,NULL);
printf("Выполнил:\n Студен 5ИНТ-2ДБ-105\n Перепечко Сергей\n Мати 2014г.\n");
system("pause");
while (count)
{
Threads[0] = _beginthread(ThreadWriter1,0,0);
Threads[1] = _beginthread(ThreadReader,0,0);
Threads[2] = _beginthread(ThreadWriter2,0,0);
Threads[1] = _beginthread(ThreadReader,0,0);
WaitForMultipleObjects(3, (HANDLE*)Threads, TRUE, INFINITE);
count--;
}
DeleteCriticalSection(&cs);
system("pause");
return 0;
}
void ThreadWriter1(void *ptr)
{
char buf[32]="1";
DWORD dw;
if(!(hMutex=CreateMutex(0, false, L"MutexWriter1"))) OpenMutex(MUTEX_ALL_ACCESS,FALSE,L"MutexWriter1");
EnterCriticalSection(&cs);
WriteFile(pipeWrite,buf,1,&dw,NULL);
printf("Writer1 write\n");
ReleaseMutex(hMutex);
LeaveCriticalSection(&cs);
_endthread();
}
void ThreadWriter2(void *ptr)
{
char buf[32]="2";
DWORD dw;
if(!(hMutex=CreateMutex(0, false, L"MutexWriter2"))) OpenMutex(MUTEX_ALL_ACCESS,FALSE,L"MutexWriter2");
EnterCriticalSection(&cs);
WriteFile(pipeWrite,buf,1,&dw,NULL);
printf("Writer2 write\n");
ReleaseMutex(hMutex);
LeaveCriticalSection(&cs);
_endthread();
}
void ThreadReader(void *ptr)
{
char buf[32]={0};
DWORD dw=0;
if(!(hMutex = CreateMutex(0, false , L"MutexReader"))) OpenMutex(MUTEX_ALL_ACCESS, false, L"MutexReader");
EnterCriticalSection(&cs);
ReadFile(pipeRead, buf, 1, &dw, 0);
//printf("\n%s\n",buf);
printf("Reader read: %s\n\n",buf);
ReleaseMutex(hMutex);
LeaveCriticalSection(&cs);
_endthread();
}