#include "stdafx.h"
#include "afxmt.h"
#include
#include
#include
using namespace std;
#define MT_INTERVAL 500
CEvent event;//定义一个通信介质,通过event实现两个线程的通信
unsigned int __stdcall Thread1(LPVOIDlp)//线程一
{
int i=0;
event.ResetEvent();
while(true)
{
cout<<"Thread1 sendnow...."<<endl;
event.SetEvent();//发信号
Sleep(100);
}
return 0;
}
unsigned int __stdcall Thread2(LPVOIDlp)
{
while(WaitForSingleObject(event,MT_INTERVAL)==WAIT_OBJECT_0)//接受信号,等待Thread1发送信号,然后执行下面的语句。
//在这个线程函数中可以通过设置MT_INTERVAL来控制这个线程的函数体多久执行一次,当事件为无信号状态时函数体隔MT_INTERVAL执行一次,当设置事件为有信号状态时,线程就执行
{
cout<<"Thread2 recievenow!"<<endl;
//WaitForSingleObject(event,INFINITE);
event.ResetEvent();
Sleep(100);
}
return 0;
}
void main()
{
HANDLE hThread1=NULL;
HANDLE hThread2=NULL;
unsigned int Tid1,Tid2;
hThread1= (HANDLE)_beginthreadex(NULL, 0,Thread1, NULL, 0, &Tid1);//开启线程一
hThread2= (HANDLE)_beginthreadex(NULL, 0,Thread2, NULL, 0, &Tid2);//开启线程二
while(1)//主线程
{
Sleep(100);
cout<<"main Threadexecute now!"<<endl;
}
if (hThread1)
{
WaitForSingleObject(hThread1,INFINITE);// 等待线程运行结束
CloseHandle(hThread1); //销毁线程
hThread1 = NULL;
}
if (hThread2)
{
WaitForSingleObject(hThread2,INFINITE);// 等待线程运行结束
CloseHandle(hThread2); //销毁线程
hThread2 = NULL;
}
return;
}