- 运行截图
- 创建事件
1 HANDLE event[4] = { 0 };//事件
- 创建线程
1 HANDLE hthread[3] = {0};//代表线程
- 创建临界区
CRITICAL_SECTION cs;
- 创建聊天缓冲区
1 volatile char str[1024] = { 0 };//代表聊天内容的缓冲区
完整代码
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <Windows.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <memory.h> 6 7 //事件 8 HANDLE event[4] = { 0 }; 9 //线程 10 HANDLE hthread[3] = { 0 }; 11 //创建临界区 12 CRITICAL_SECTION cs1; 13 14 char str[1024] = { 0 };//代表聊天内容的缓冲区 15
//中间者 16 DWORD WINAPI zhong(void *p) 17 { 18 int i = 0; 19 while (++i) 20 { 21 //等待boy发送的事件0再继续执行 22 WaitForSingleObject(event[0], INFINITE); 23 ResetEvent(event[0]); 24 EnterCriticalSection(&cs1); 25 printf("%s ", str); 26 LeaveCriticalSection(&cs1); 27 28 //发送事件1 29 SetEvent(event[1]); 30 31 32 //等待girl发送的事件2再继续执行 33 WaitForSingleObject(event[2], INFINITE); 34 ResetEvent(event[2]); 35 EnterCriticalSection(&cs1); 36 printf("%s ", str); 37 LeaveCriticalSection(&cs1); 38 //发送事件3 39 SetEvent(event[3]); 40 41 Sleep(1000); 42 } 43 } 44 45 DWORD WINAPI boy(void *p) 46 { 47 int i = 0; 48 while (++i) 49 { 50 EnterCriticalSection(&cs1); 51 memset(str, '