C++使用事件对象实现多线程

来源:互联网 发布:小说 炫浪网络社区 编辑:程序博客网 时间:2024/06/11 01:46

// 20101112.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
int num=1;
HANDLE hEvent;

unsigned long _stdcall ThreadProc1(void *lpParameter)  
{
while(num<100)
{  
   WaitForSingleObject(hEvent,INFINITE);
   cout<<"线程1当前计数"<<num<<endl;
   num++;
   Sleep(100);
   SetEvent(hEvent);
}
return 0;
}

unsigned long _stdcall ThreadProc2(void *lpParameter)
{
while(num<100)
{
   WaitForSingleObject(hEvent,INFINITE);
   cout<<"线程2当前计数"<<num<<endl;
   num++;
   Sleep(100);
   SetEvent(hEvent);
}
return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hThread1=CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
HANDLE hThread2=CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
hEvent=CreateEvent(NULL,0,TRUE,_T("event"));
CloseHandle(hThread1);
CloseHandle(hThread2);
while(true)
{
   ;
}

return 0;

}

0 0