⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myevent.cpp

📁 Visual C++高级编程及其项目应用开发(含源代码)
💻 CPP
字号:
// MyEvent.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "MyEvent.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

DWORD threadA(void* pD)
{
	int iID=(int)pD;
	//在内部重新打开
	HANDLE hCounterIn=OpenEvent(EVENT_ALL_ACCESS,FALSE,"My Try");

	printf("\tthread %d begin\n",iID);
	//设置成为有信号状态
	Sleep(1000);
	SetEvent(hCounterIn);
	Sleep(1000);
	printf("\tthread %d end\n",iID);
	CloseHandle(hCounterIn);
	return 0;
}

DWORD threadB(void* pD)
{
	//等待threadA结束后再继续执行
	int iID=(int)pD;
	//在内部重新打开
	HANDLE hCounterIn=OpenEvent(EVENT_ALL_ACCESS,FALSE,"My Try");

	if(WAIT_TIMEOUT == WaitForSingleObject(hCounterIn,10*1000))
	{
		printf("\t\tthread %d wait time out\n",iID);
	}
	else
	{
		printf("\t\tthread %d wait ok\n",iID);
	}
	CloseHandle(hCounterIn);
	return 0;
}

void main()
{
	HANDLE hCounter=NULL;
	if( (hCounter=OpenEvent(EVENT_ALL_ACCESS,FALSE,"My Try"))==NULL)
	{
		//如果没有其他进程创建这个事件,则重新创建,该事件为人工重置事件
		hCounter = CreateEvent(NULL,TRUE,FALSE,"My Try");
	}

	//创建线程
	HANDLE hThread[3];
	printf("test of manual rest event\n");
	CWinThread* pT1=AfxBeginThread((AFX_THREADPROC)threadA,(void*)1);
	CWinThread* pT2=AfxBeginThread((AFX_THREADPROC)threadB,(void*)2);
	CWinThread* pT3=AfxBeginThread((AFX_THREADPROC)threadB,(void*)3);
	hThread[0]=pT1->m_hThread;
	hThread[1]=pT2->m_hThread;
	hThread[2]=pT3->m_hThread;
	//等待线程结束
	WaitForMultipleObjects(3,hThread,TRUE,INFINITE);
	//关闭句柄
	CloseHandle(hCounter);

	if( (hCounter=OpenEvent(EVENT_ALL_ACCESS,FALSE,"My Try"))==NULL)
	{
		//如果没有其他进程创建这个事件,则重新创建,该事件为自动重置事件
		hCounter = CreateEvent(NULL,FALSE,FALSE,"My Try");
	}
	//创建线程
	printf("test of auto rest event\n");
	pT1=AfxBeginThread((AFX_THREADPROC)threadA,(void*)1);
	pT2=AfxBeginThread((AFX_THREADPROC)threadB,(void*)2);
	pT3=AfxBeginThread((AFX_THREADPROC)threadB,(void*)3);
	hThread[0]=pT1->m_hThread;
	hThread[1]=pT2->m_hThread;
	hThread[2]=pT3->m_hThread;
	//等待线程结束
	WaitForMultipleObjects(3,hThread,TRUE,INFINITE);
	//关闭句柄
	CloseHandle(hCounter);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -