-
Notifications
You must be signed in to change notification settings - Fork 0
/
P-V_Mutex.cpp
53 lines (46 loc) · 928 Bytes
/
P-V_Mutex.cpp
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
#include <iostream>
#include <Windows.h>
/*
互斥量(Mutxe)
function:
HANDLE CreateMutex(
LPSECURITY_ATTRIBUTES IpMutexAttributes,
BOOL BInitialOwner, //初始化互斥量的状态:真或假
LPCTSTR IpName //名字,可以为NULL但不能跨进程使用
);
HANDLE OpenMutex(
DWORD dwDesiredAccess,
BOOL BInheritHandle,
LPCTSTR IpName
);
BOOL ReleaseMutex(
HANDLE hMutex
);
CloseMutex(
HANDLE hObject
);
*/
using namespace::std;
int nSum = 0;
int NUMBER = 80000;
HANDLE hThread[2];
CRITICAL_SECTION cs;
DWORD WINAPI Accumulate(LPVOID lpaaram)
{
for (int i(0); i < NUMBER; i++)
{
int iCopy = nSum;
nSum = iCopy + 1;
}
return 0;
}
int main()
{
HANDLE mutex = CreateMutex(NULL, true, NULL);
InitializeCriticalSection(&cs);
hThread[0] = CreateThread(NULL, 0, Accumulate, NULL, 0, NULL);
hThread[1] = CreateThread(NULL, 0, Accumulate, NULL, 0, NULL);
WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
cout << nSum << endl;
return 0;
}