事件对象的使用
// 07 事件对象的使用.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <windows.h> int g_n; HANDLE hEvent; DWORD WINAPI ThreadPro1(LPVOID lpThreadParameter){ for (int i = 0; i < 10000000; i++) { WaitForSingleObject(hEvent, -1); g_n++; printf("我在线程1:%d\n", g_n); Sleep(100); SetEvent(hEvent); } return 0; } DWORD WINAPI ThreadPro2(LPVOID lpThreadParameter){ for (int i = 0; i < 10000000; i++) { WaitForSingleObject(hEvent, -1); g_n++; printf("我在线程2:%d\n", g_n); Sleep(100); SetEvent(hEvent); } return 0; } int _tmain(int argc, _TCHAR* argv[]){ HANDLE hThread1 = 0, hThread2; //创建一个事件对象 hEvent = CreateEvent( NULL, //安全属性 FALSE, //自动重置 TRUE, //初始状态为激发态(有信号状态) NULL //事件对象的名字 ); hThread1 = CreateThread(NULL, NULL, ThreadPro1, NULL, NULL, NULL); hThread2 = CreateThread(NULL, NULL, ThreadPro2, NULL, NULL, NULL); WaitForSingleObject(hThread1, -1); WaitForSingleObject(hThread2, -1); printf("%d", g_n); return 0; }
让数据变得更安全!