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
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>
#include <locale>
UINT WINAPI ThreadWriter1(void *ptr);
UINT WINAPI ThreadWriter2(void *ptr);
UINT WINAPI ThreadReader(void *ptr);
HANDLE hSem, pipeRead, pipeWrite;
uintptr_t Threads[3];
int count = 1000;
int _tmain(int argc, _TCHAR* argv[])
{
setlocale(LC_ALL, "Russian");
CreatePipe(&pipeRead,&pipeWrite,NULL,NULL);
system("pause");
while (count)
{
Threads[0] = _beginthreadex(0,0,ThreadWriter1,0,0,0);
Threads[1] = _beginthreadex(0,0,ThreadReader,0,0,0);
Threads[2] = _beginthreadex(0,0,ThreadWriter2,0,0,0);
Threads[1] = _beginthreadex(0,0,ThreadReader,0,0,0);
WaitForMultipleObjects(3, (HANDLE*)Threads, TRUE, INFINITE);
count--;
}
system("pause");
return 0;
}
UINT WINAPI ThreadWriter1(void *ptr)
{
char buf[32]="1";
DWORD dw;
if (!(hSem = CreateSemaphore(0,1,1,L"my_sem")))
OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,L"my_sem");
WriteFile(pipeWrite,buf,1,&dw,NULL);
printf("Writer1 write\n");
ReleaseSemaphore(hSem,1,0);
return 0;
}
UINT WINAPI ThreadWriter2(void *ptr)
{
char buf[32]="2";
DWORD dw;
if (!(hSem = CreateSemaphore(0,1,1,L"my_sem")))
OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,L"my_sem");
WriteFile(pipeWrite,buf,1,&dw,NULL);
printf("Writer2 write\n");
ReleaseSemaphore(hSem,1,0);
return 0;
}
UINT WINAPI ThreadReader(void *ptr)
{
char buf[32]={0};
DWORD dw=0;
if (!(hSem = CreateSemaphore(0,1,1,L"my_sem")))
OpenSemaphore(SEMAPHORE_ALL_ACCESS,FALSE,L"my_sem");
ReadFile(pipeRead, buf, 1, &dw, 0);
printf("Reader read: %s\n\n",buf);
ReleaseSemaphore(hSem,1,0);
return 0;
}