//
#include "stdafx.h"
#include <stdio.h>
#include <process.h>
#include <windows.h>
long g_nNum;
unsigned int __stdcall Fun(void *pPM);
const int THREAD_NUM = 10;
CRITICAL_SECTION g_csThreadCode;
HANDLE g_hEvent;
int main()
{
/*
LPSECURITY_ATTRIBUTES lpEventAttributes,
BOOL bManualReset, 手动置位
BOOL bInitialState, true有信号,false无信号
LPCWSTR lpName
*/
g_hEvent = CreateEvent(NULL,FALSE,FALSE,NULL);//第3个参数必须为false,需要让主线程等待。
InitializeCriticalSection(&g_csThreadCode);
HANDLE handle[THREAD_NUM];
g_nNum = 0;
int i = 0;
while (i < THREAD_NUM)
{
handle[i] = (HANDLE)_beginthreadex(NULL, 0, Fun, &i, 0, NULL);
WaitForSingleObject(g_hEvent, INFINITE); //等待事件有信号
i++;
}
WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
CloseHandle(g_hEvent);
DeleteCriticalSection(&g_csThreadCode);
for (i = 0; i < THREAD_NUM; i++)
CloseHandle(handle[i]);
return 0;
}
unsigned int __stdcall Fun(void *pPM)
{
int nThreadNum = *(int *)pPM;
SetEvent(g_hEvent);
Sleep(50);//some work should to do
EnterCriticalSection(&g_csThreadCode);
g_nNum++;
Sleep(0);//some work should to do
printf("线程编号为%d 全局资源值为%d\n", nThreadNum, g_nNum);
LeaveCriticalSection(&g_csThreadCode);
return 0;
}
备注:CreateEvent(NULL,FALSE,FALSE,NULL);//第3个参数必须为false,需要让主线程等待。
如果为自动置位,则对该事件调用WaitForSingleObject()后会自动调用ResetEvent()使事件变成未触发状态。