www.pudn.com > dialogic_IVR.rar > CriticalResource.cpp


// 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); 
}