#include <Windows.h>
#include <stdio.h>
const unsigned int THREAD_NUM = 3;
#define DATA_EVENT_SIZE 4 //事件总数
enum data_event_id { One, Two, Three, Four }; //事件标
HANDLE data_event_array[DATA_EVENT_SIZE]; //事件句柄数组
DWORD WINAPI ThreadFunc(LPVOID p)
{
printf("I am a child thread 0 which pid is %d ...\n", GetCurrentThreadId()); //输出子线程pid
Sleep(500);
SetEvent(data_event_array[One]);
printf("The child thread 0 which pid is %d quit ...\n", GetCurrentThreadId());
return 0;
}
DWORD WINAPI ThreadFunc1(LPVOID p)
{
printf("I am a child thread 1 which pid is %d ...\n", GetCurrentThreadId()); //输出子线程pid
Sleep(2000);
SetEvent(data_event_array[Two]);
printf("The child thread 1 which pid is %d quit ...\n", GetCurrentThreadId());
return 0;
}
DWORD WINAPI ThreadFunc2(LPVOID p)
{
printf("I am a child thread 2 which pid is %d ...\n", GetCurrentThreadId()); //输出子线程pid
Sleep(4000);
SetEvent(data_event_array[Three]);
printf("The child thread 2 which pid is %d quit ...,After SetEvent Three\n", GetCurrentThreadId());
SetEvent(data_event_array[Four]);
printf("The child thread 2 which pid is %d quit ...,After SetEvent Four\n", GetCurrentThreadId());
return 0;
}
int main()
{
printf("I am the main thread that pid is %d ...\n", GetCurrentThreadId()); //输出主线程pid
HANDLE hThread[THREAD_NUM];
hThread[0] = CreateThread(NULL, 0, ThreadFunc, 0, 0, NULL); // 创建线程
hThread[1] = CreateThread(NULL, 0, ThreadFunc1, 0, 0, NULL); // 创建线程
hThread[2] = CreateThread(NULL, 0, ThreadFunc2, 0, 0, NULL); // 创建线程
//创建初始状态为无信号,触发后自动复位的事件
data_event_array[One] = CreateEvent(NULL, FALSE, FALSE, NULL);
data_event_array[Two] = CreateEvent(NULL, FALSE, FALSE, NULL);
data_event_array[Three] = CreateEvent(NULL, FALSE, FALSE, NULL);
data_event_array[Four] = CreateEvent(NULL, FALSE, FALSE, NULL);
int resulut = 0;
while (1)
{
resulut = WaitForMultipleObjects(DATA_EVENT_SIZE, data_event_array, FALSE, INFINITE); //只要有一个线程返回就结束
Sleep(30);
if (WAIT_OBJECT_0 == resulut)
{
printf("get the event one!\n");
}
else if (WAIT_OBJECT_0 + 1 == resulut)
{
printf("get the event two!\n");
}
else if (WAIT_OBJECT_0 + 2 == resulut)
{
printf("get the event three!\n");
}
else if (WAIT_OBJECT_0 + 3 == resulut)
{
printf("get the event four!\n");
}
else if (WAIT_FAILED == resulut)
{
printf("The fuction WaitForMultipleObjects error! \n");
}
}
printf("The main thread which pid is %d quit ...\n", GetCurrentThreadId());
return 0;
}
输出如下: