【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;
}

猜你喜欢

转载自blog.csdn.net/cssxn/article/details/80637994