// wondows原理day002.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<windows.h> //3个全局事件对象句柄 HANDLE hEventA, hEventB, hEventC; //线程A DWORD WINAPI ThreadProc1(_In_ LPVOID lpParameter) { for (int i = 0; i < 10; i++) { WaitForSingleObject(hEventA, -1); printf("A "); //关闭自己,打开下一个要打印的事件对象 ResetEvent(hEventA); SetEvent(hEventB); } return 0; } //线程B DWORD WINAPI ThreadProc2(_In_ LPVOID lpParameter) { for (int i = 0; i < 10; i++) { WaitForSingleObject(hEventB, -1); printf("B "); //关闭自己,打开下一个要打印的事件对象 ResetEvent(hEventB); SetEvent(hEventC); } return 0; } //线程C DWORD WINAPI ThreadProc3(_In_ LPVOID lpParameter) { for (int i = 0; i < 10; i++) { WaitForSingleObject(hEventC, -1); printf("C "); //关闭自己,打开下一个要打印的事件对象 ResetEvent(hEventC); SetEvent(hEventA); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { //创建3个事件对象 hEventA = CreateEvent(NULL, TRUE, TRUE, L"A"); hEventB = CreateEvent(NULL, TRUE, FALSE, L"B"); hEventC = CreateEvent(NULL, TRUE, FALSE, L"C"); //创建3个线程,分别实现打印A,B,C HANDLE hThread1 = CreateThread(NULL, NULL, ThreadProc1, NULL, NULL,NULL); HANDLE hThread2 = CreateThread(NULL, NULL, ThreadProc2, NULL, NULL, NULL); HANDLE hThread3 = CreateThread(NULL, NULL, ThreadProc3, NULL, NULL, NULL); //等待线程返回 WaitForSingleObject(hThread1, -1); WaitForSingleObject(hThread2, -1); WaitForSingleObject(hThread3, -1); HANDLE arrHandle[] = { hThread1, hThread2, hThread3 }; //也可以用下面的多对象等待 //WaitForMultipleObjects(3,arrHandle,TRUE,INFINITE) system("pause"); return 0; }