大家可以自己试试实现,得分别用一个线程打印A,B,C
代码:
#include "stdio.h"
#include <windows.h>
DWORD WINAPI ThreadA(LPVOID parameter) {
HANDLE* eventHandle = (HANDLE*)parameter;
//等待A通知,通知后执行下面代码并修改A为未通知(原因如下)
//CreateEvent(NULL ,FALSE ,TRUE ,NULL); 第二个参数为FALSE
WaitForSingleObject(eventHandle[0] ,-1);
printf("A");
//设置事件B为已通知,接下来的代码逻辑差不多,就是A->B->C->A.......
SetEvent(eventHandle[1]);
return 0;
}
DWORD WINAPI ThreadB(LPVOID parameter) {
HANDLE* eventHandle = (HANDLE*)parameter;
WaitForSingleObject(eventHandle[1] ,-1);
printf("B");
SetEvent(eventHandle[2]);
return 0;
}
DWORD WINAPI ThreadC(LPVOID parameter) {
HANDLE* eventHandle = (HANDLE*)parameter;
WaitForSingleObject(eventHandle[2] ,-1);
printf("C\n");
SetEvent(eventHandle[0]);
return 0;
}
DWORD WINAPI ThreadCreate(LPVOID parameter) {
//事件句柄数组
HANDLE eventHandle[3] = { 0 };
eventHandle[0] = CreateEvent(NULL ,FALSE ,TRUE ,NULL);
eventHandle[1] = CreateEvent(NULL ,FALSE ,FALSE ,NULL);
eventHandle[2] = CreateEvent(NULL ,FALSE ,FALSE ,NULL);
//线程句柄数组
HANDLE hThread[3] = { 0 };
for ( size_t i = 0; i < 10; i++ ) {
hThread[0] = CreateThread(0 ,0 ,ThreadA ,(LPVOID)eventHandle ,0 ,0);
hThread[1] = CreateThread(0 ,0 ,ThreadB ,(LPVOID)eventHandle ,0 ,0);
hThread[2] = CreateThread(0 ,0 ,ThreadC ,(LPVOID)eventHandle ,0 ,0);
//等待所有线程跑完
WaitForMultipleObjects(3,hThread ,TRUE,-1);
//关闭所有线程句柄
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
CloseHandle(hThread[2]);
}
//关闭所有线程句柄
CloseHandle(eventHandle[0]);
CloseHandle(eventHandle[1]);
CloseHandle(eventHandle[2]);
return 0;
}
int main(int argc ,char* argv[]) {
//创建线程避免卡死主线程
CreateThread(0,0,ThreadCreate,0,0,0);
//让线程跑一会,直到输入任意字符
getchar();
return 0;
}