criticalresource.cpp

来自「基于dialogic语音卡的IVR系统源代码」· C++ 代码 · 共 86 行

CPP
86
字号
// CriticalResource.cpp: implementation of the CCriticalResource class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "CriticalResource.h"

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

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CCriticalResource::CCriticalResource()
{
	m_hSemaphore = NULL;
}

CCriticalResource::~CCriticalResource()
{
	if(m_hSemaphore != NULL)
	{
		CloseHandle(m_hSemaphore);
	}
}

int CCriticalResource::Create(char *szName, int nWaitTime)
{
	m_nWaitTime = nWaitTime;
	if( (m_hSemaphore = CreateSemaphore(NULL, 1, 1, szName)) == NULL )
	{
		return(-1);
	}

	return(0);
}

int CCriticalResource::Lock()
{
DWORD dwResult;

	dwResult = WaitForSingleObject(m_hSemaphore, m_nWaitTime);

	if(dwResult == WAIT_TIMEOUT)
	{//超时
		return(-1);
	}
	if(dwResult == WAIT_OBJECT_0)
	{//成功锁定
		return(0);
	}
	if(dwResult == WAIT_ABANDONED)
	{
		return(1);
	}

	return(-1);
}

int CCriticalResource::Unlock()
{
BOOL bResult;
LONG lPreviousCount = 0;

	bResult = ReleaseSemaphore(m_hSemaphore, 1, &lPreviousCount);

	if(bResult == FALSE)
	{//解锁失败
//		dwErrorCode = GetLastError();
//		char szTemp[100];
//		itoa(dwErrorCode, szTemp, 10);
//		AfxMessageBox(szTemp);
		return(-1);
	}
	if(bResult == TRUE)
	{//成功解锁
		return(0);
	}

	return(-1);
}

⌨️ 快捷键说明

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