c++ winapi 多线程通信之事件机制

功能介绍

本次作业实现了使用event事件机制进行线程间通信控制,控制两个子进程实现1到100000的累加,第一个子进程thread1负责偶数的累加,第二个子进程thread2负责基数的累加,最终得出计算结果为5000050000,经过res函数验证结果正确。

实现代码 c++

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
#include<Windows.h>
#include<iostream>
#include<string>
using namespace std;
long long sum = 0;
int maxn = 100000;
CRITICAL_SECTION cs;
DWORD WINAPI thread1(PVOID pvParam) {
//进入临界区后进行屏幕输出,防止两个线程同时输出导致输出混乱
EnterCriticalSection(&cs);
cout << "Threat1 is running!" << endl;
LeaveCriticalSection(&cs);
//打开event1事件
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("event1"));
for (int i = 0; i <= maxn; i += 2) {
//等待event1为受信状态后向下执行
WaitForSingleObject(hEvent, INFINITE);
//cout << "hevent1 is true" << endl;
//设置event1 为未受信状态,防止其他线程操作
//ResetEvent(hEvent);
sum += i;
//操作结束后更改event1为受信状态,允许其他子线程访问
SetEvent(hEvent);
}
return 0;
}
DWORD WINAPI thread2(PVOID pvParam) {
EnterCriticalSection(&cs);
cout << "Threat2 is running!" << endl;
LeaveCriticalSection(&cs);
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, TRUE, TEXT("event1"));
for (int i = 1; i <= maxn; i += 2) {
WaitForSingleObject(hEvent, INFINITE);
//ResetEvent(hEvent);
sum += i;
SetEvent(hEvent);
}
return 0;
}
long long res() {
long long s = 0;
for (int i = 1; i <= maxn; i++) {
s += i;
}
return s;
}
int main() {
InitializeCriticalSection(&cs);
//创建事件event1
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, TEXT("event1"));
//CreateEvent()参数分别表示安全属性、人工重置选项、初始受信状态、对象名,第二个False表示不使用人工重置即自动重置,在event被获取到后(WaitForSingleObject)自动变为未受信状态,不需要使用ResetEvent进行状态变更
//text()作用是实现对字符处理的透明化,不论是否使用 unicode 字符集,使用 TEXT 宏都可以使程序正常使用,
//如果程序中有 unicode 宏的,那么就使用宽字符,否则使用单字节字符,保证程序的可移植性
cout << "event1 was created and fIinitialState is False \n";
//设置event1事件为受信状态
SetEvent(hEvent);
//创建子进程threat1和threat2
HANDLE hThreat1 = CreateThread(NULL, 0, thread1, NULL, 0, NULL);
HANDLE hThreat2 = CreateThread(NULL, 0, thread2, NULL, 0, NULL);
EnterCriticalSection(&cs);
cout << "threat1 and threat2 were created!\n";
LeaveCriticalSection(&cs);

//ResumeThread(hThreat1);
//ResumeThread(hThreat1);
HANDLE hThreats[2] = { hThreat1,hThreat2 };
WaitForMultipleObjects(2, hThreats, TRUE, INFINITE);
cout << "Mutil threats result of the sum from 1 to "<<maxn<<" is " << sum << endl;
cout << "Right result of the sum from 1 to " << maxn << " is " << res() << endl;
return 0;
}