1. 程式人生 > >【Windows原理】執行緒同步-事件物件

【Windows原理】執行緒同步-事件物件

#include "stdafx.h"
#include <windows.h>
HANDLE g_hEventA = nullptr;
HANDLE g_hEventB = nullptr;
DWORD WINAPI ThreadProcA(LPVOID lpParam)
{
   /*
    * 如果是自動狀態
    * WaitForSingleObject成功後會把等待物件變為無訊號狀態
    * 如果是手動
    * WaitForSingleObject返回,什麼都不幹,需要手動ResetEvent
    **/
    for (int i = 0; i < 10
;i+=2) { WaitForSingleObject(g_hEventA, INFINITE); printf("A === %d \n", i); SetEvent(g_hEventB); } return 0; } DWORD WINAPI ThreadProcB(LPVOID lpParam) { for (int i = 1; i < 10; i += 2) { WaitForSingleObject(g_hEventB, INFINITE); printf("B === %d \n"
, i); SetEvent(g_hEventA); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { /* * 建立事件物件 * 引數1:安全屬性,預設 * 引數2:TRUE手動,FALSE自動 * 引數3:初始狀態,TRUE有訊號,FALSE無訊號 * 引數4:事件物件有無名字 **/ if (!(g_hEventA = CreateEvent(NULL, FALSE, TRUE, NULL)))return 0; if (!(g_hEventB = CreateEvent(NULL
, FALSE, TRUE, NULL)))return 0; HANDLE hHandle[2] = {}; hHandle[0] = CreateThread(NULL, 0, ThreadProcA, NULL, 0, NULL); hHandle[1] = CreateThread(NULL, 0, ThreadProcB, NULL, 0, NULL); // 等待所有執行緒全部返回 WaitForMultipleObjects(2, hHandle, TRUE, INFINITE); system("pause"); return 0; }