这是<计算机病毒揭秘与对抗>那书p125页的例子...
下面使用时件对象来同步控制先前引爆炸弹的例子
#include <stdio.h> #include <windows.h> #include <process.h> BOOL g_bContinue = TRUE; //用于通知线程退出的标志变量 int g_nCount1 = 0; UINT __stdcall ThreadFunc1(LPVOID); UINT __stdcall ThreadFunc2(LPVOID); HANDLE g_hEvent; //用于同步控制的全局事件对象句柄 int main(int argc, char* argv[]) { UINT uId; HANDLE h[2]; //创建一个自动重置匿名的初始状态为受信的事件对象 g_hEvent = CreateEvent(NULL, FALSE, TRUE, NULL); h[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc2, NULL, 0, &uId); h[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunc1, NULL, 0, &uId); // 等待500毫秒后通知两个计数线程结束,关闭句柄 Sleep(500); g_bContinue = FALSE; //通知两个线程退出 WaitForMultipleObjects(2, h, TRUE, INFINITE); //等待两个线程都退出 CloseHandle(h[0]); //关闭线程1的句柄 CloseHandle(h[1]); //关闭线程2的句柄 CloseHandle(g_hEvent);//关闭事件对象句柄 return 0; } UINT __stdcall ThreadFunc1(LPVOID) { while(g_bContinue) { WaitForSingleObject(g_hEvent, INFINITE); //等待事件对象受信 g_nCount1++; printf(" -> 装入一颗炸弹\n"); SetEvent(g_hEvent); //将事件对象置为受信状态 } return 0; } UINT __stdcall ThreadFunc2(LPVOID) { while(g_bContinue) { WaitForSingleObject(g_hEvent, INFINITE); //等待事件对象受信 if (g_nCount1 != 0) { printf("** 同时引爆 %d 颗炸弹\n\n", g_nCount1); g_nCount1 = 0; } SetEvent(g_hEvent); //将事件对象置为受信状态 } return 0; }