以下程序用通知事件和临界区来同步
// Multhread.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <process.h>
#include <windows.h>//for HANDLE
using namespace std;
long g_nNum;
unsigned int __stdcall Fun(void* pPM);
const int THREAD_NUM = 10;
HANDLE g_hThreadEvent;
//临界区
CRITICAL_SECTION g_csThreadCode;
int main()
{
printf("线程同步事件\n");
g_hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
InitializeCriticalSection(&g_csThreadCode);
HANDLE handle[THREAD_NUM];
g_nNum = 0;
int i = 0;
while (i < THREAD_NUM)
{
//创建NUM个线程
handle[i] = (HANDLE)_beginthreadex(NULL, 0, Fun, &i, 0, NULL);
WaitForSingleObject(g_hThreadEvent, INFINITE);
++i;
}
//等待所有线程运行完毕
WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
//销毁事件和关键段
CloseHandle(g_hThreadEvent);
DeleteCriticalSection(&g_csThreadCode);
getchar();
return 0;
}
unsigned int __stdcall Fun(void* pPM)
{
int nThreadNum = *(int *)pPM;
SetEvent(g_hThreadEvent);
Sleep(50);
EnterCriticalSection(&g_csThreadCode);//进入临界区
g_nNum++;
//Sleep(10);
cout << "\n线程ID = " << nThreadNum << " 全局资源值为: " << g_nNum;
LeaveCriticalSection(&g_csThreadCode);//退出临界区
return 0;
}