#include "stdafx.h"
#include <windows.h>
HANDLE g_hSet = NULL;
HANDLE g_hClean = NULL;
int g_max = 10;
int g_num = 0;
DWORD WINAPI t1(LPVOID lpargv)
{
for(int i =0;i<g_max;i++)
{
WaitForSingleObject(g_hSet,INFINITE);
g_num = 1;
//Sleep(100);
printf("线程1执行了 %d\n",g_num);
SetEvent(g_hClean);
}
return 0;
}
DWORD WINAPI t2(LPVOID lpargv)
{
for(int i =0;i<g_max;i++)
{
WaitForSingleObject(g_hClean,INFINITE);
g_num = 0;
//Sleep(100);
printf("线程2执行了 %d\n",g_num);
SetEvent(g_hSet);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
//第二个参数true通知类型,false互斥类型
g_hSet = CreateEvent(NULL,FALSE,TRUE,NULL);
g_hClean = CreateEvent(NULL,FALSE,FALSE,NULL);
HANDLE hThread[2];
hThread[0] = CreateThread(NULL,0,t1,NULL,0,NULL);
hThread[1] = CreateThread(NULL,0,t2,NULL,0,NULL);
WaitForMultipleObjects(2,hThread,TRUE,INFINITE);
CloseHandle(hThread[0]);
CloseHandle(hThread[1]);
CloseHandle(g_hSet);
CloseHandle(g_hClean);
return 0;
}
网友评论