-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathczxt12.cpp
More file actions
58 lines (47 loc) · 1.63 KB
/
czxt12.cpp
File metadata and controls
58 lines (47 loc) · 1.63 KB
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
#include <windows.h>
#include <iostream>
CRITICAL_SECTION cs;
int count = 0; // 全局共享变量
// 线程1函数
DWORD WINAPI Thread1Proc(LPVOID lpParameter) {
for (int i = 0; i < 5; ++i) {
EnterCriticalSection(&cs); // 进入临界区
count++;
std::cout << "线程1:count = " << count << std::endl;
Sleep(500);
LeaveCriticalSection(&cs); // 退出临界区
}
return 0;
}
// 线程2函数
DWORD WINAPI Thread2Proc(LPVOID lpParameter) {
for (int i = 0; i < 5; ++i) {
EnterCriticalSection(&cs); // 进入临界区
count++;
std::cout << "线程2:count = " << count << std::endl;
Sleep(500);
LeaveCriticalSection(&cs); // 退出临界区
}
return 0;
}
int main() {
std::cout << "计算机25-5齐浩凯2404010526" << std::endl;
InitializeCriticalSection(&cs);
std::cout << "主线程:创建两个子线程..." << std::endl;
HANDLE hThread1 = CreateThread(NULL, 0, Thread1Proc, NULL, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, Thread2Proc, NULL, 0, NULL);
if (hThread1 == NULL || hThread2 == NULL) {
std::cerr << "创建线程失败!错误码:" << GetLastError() << std::endl;
DeleteCriticalSection(&cs);
return 1;
}
// 等待两个子线程执行完毕
HANDLE hThreads[] = {hThread1, hThread2};
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
std::cout << "主线程:所有线程执行完毕,最终count = " << count << std::endl;
// 清理资源
CloseHandle(hThread1);
CloseHandle(hThread2);
DeleteCriticalSection(&cs);
return 0;
}