1. 程式人生 > >【Windows原理】執行緒同步-訊號量

【Windows原理】執行緒同步-訊號量

#include "stdafx.h"
#include <windows.h>

int g_num = 0;
HANDLE g_hSemaphore = nullptr;

DWORD WINAPI ThreadProc(LPVOID lpParam)
{

    for (int i = 0; i < 5;i++)
    {
        // WaitForSingleObject會自動把g_hSemaphore - 1;
        WaitForSingleObject(g_hSemaphore, INFINITE);
        printf("%d "
, i); ReleaseSemaphore(g_hSemaphore, 1, NULL); } return 0; } int _tmain(int argc, _TCHAR* argv[]) { if (!(g_hSemaphore = CreateSemaphore(NULL, 0, 2, NULL)))return 0; HANDLE hHandle[2] = { 0 }; hHandle[0] = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL); hHandle[1] = CreateThread(NULL
, 0, ThreadProc, NULL, 0, NULL); // 等待返回 ReleaseSemaphore(g_hSemaphore, 1, NULL); WaitForMultipleObjects(2, hHandle, TRUE, INFINITE); system("pause"); return 0; }