-
Notifications
You must be signed in to change notification settings - Fork 0
/
MUTEX.cpp
47 lines (35 loc) · 1.08 KB
/
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
#include <iostream>
#include <windows.h>
using namespace std;
HANDLE mutex;
int sharedVariable = 0;
void increment() {
// Çàõîïëåííÿ ì'þòåêñó
WaitForSingleObject(mutex, INFINITE);
// Çá³ëüøåííÿ ñï³ëüíî¿ çì³ííî¿ íà 1
sharedVariable++;
// Çâ³ëüíåííÿ ì'þòåêñó
ReleaseMutex(mutex);
}
int main() {
mutex = CreateMutex(NULL, FALSE, L"L5_Mutex");
if (mutex == NULL) {
cout << "Failed to create mutex." << endl;
return 1;
}
// Ñòâîðåííÿ 3 ïîòîê³â, êîæåí ç ÿêèõ áóäå çá³ëüøóâàòè ñï³ëüíó çì³ííó íà 1
HANDLE threads[3];
for (int i = 0; i < 3; i++) {
threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)increment, NULL, 0, NULL);
}
// Î÷³êóâàííÿ çàâåðøåííÿ âñ³õ ïîòîê³â
WaitForMultipleObjects(3, threads, TRUE, INFINITE);
// Âèâåäåííÿ çíà÷åííÿ ñï³ëüíî¿ çì³ííî¿
cout << "Shared variable: " << sharedVariable << endl;
// Çâ³ëüíåííÿ ðåñóðñ³â
CloseHandle(mutex);
for (int i = 0; i < 3; i++) {
CloseHandle(threads[i]);
}
return 0;
}