Repository navigation
Expand file tree
/
Copy pathWeek4_Win_IntFile.cpp
More file actions
96 lines (84 loc) · 2.31 KB
/
Copy pathWeek4_Win_IntFile.cpp
File metadata and controls
96 lines (84 loc) · 2.31 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <stdio.h>
#include <windows.h>
// 共享变量
int sharedVar1 = 0;
int sharedVar2 = 0;
int running = 1; // 控制线程运行的标志
// 线程函数声明
DWORD WINAPI threadFunctionA(LPVOID arg);
DWORD WINAPI threadFunctionB(LPVOID arg);
DWORD WINAPI threadFunctionC(LPVOID arg);
int main(void) {
DWORD tid1, tid2, tid3; // 线程 ID
HANDLE th1, th2, th3; // 线程句柄
// 创建 3 个线程
th1 = CreateThread(
NULL, // 默认安全属性
0, // 默认栈大小
threadFunctionA, // 线程函数
NULL, // 线程函数参数
0, // 默认创建标志
&tid1 // 返回的线程 ID
);
th2 = CreateThread(
NULL,
0,
threadFunctionB,
NULL,
0,
&tid2
);
th3 = CreateThread(
NULL,
0,
threadFunctionC,
NULL,
0,
&tid3
);
// 等待所有线程完成
if (th1 != NULL && th2 != NULL && th3 != NULL) {
WaitForSingleObject(th1, INFINITE);
WaitForSingleObject(th2, INFINITE);
WaitForSingleObject(th3, INFINITE);
// 关闭线程句柄
CloseHandle(th1);
CloseHandle(th2);
CloseHandle(th3);
}
return 0;
}
// 线程A:等待用户输入两个整数值
DWORD WINAPI threadFunctionA(LPVOID arg) {
while (1) {
printf("请输入两个整数值:\n");
scanf_s("%d %d", &sharedVar1, &sharedVar2);
if (sharedVar1 < 0) {
running = 0; // 设置终止标志
break;
}
}
return 0;
}
// 线程B:计算并显示两个共享变量的和
DWORD WINAPI threadFunctionB(LPVOID arg) {
while (running) {
printf("和:%d\n", sharedVar1 + sharedVar2);
Sleep(2000); // 等待2秒
if (sharedVar1 < 0) {
break;
}
}
return 0;
}
// 线程C:计算并显示两个共享变量的乘积
DWORD WINAPI threadFunctionC(LPVOID arg) {
while (running) {
printf("乘积:%d\n", sharedVar1 * sharedVar2);
Sleep(3000); // 等待3秒
if (sharedVar1 < 0) {
break;
}
}
return 0;
}