// Mutex.cpp: implementation of the CMutex class.
//
//////////////////////////////////////////////////////////////////////

#include "Mutex.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#ifdef	IMPL_NO_CRITICAL_SECTION
//#error no critical section
//void fn(void)
//{
//	CRITICAL_SECTION	cs;
//	InitializeCriticalSection(&cs);
//	TryEnterCriticalSection(&cs);
//	LeaveCriticalSection(&cs);
//}

//==============================================================================
// Method      : 
// Description : 
// Paramter    : 
// Return      : 
// Note        : 
// Update Date : 
//==============================================================================

CMutex::CMutex()
{

	memset((void*)&m_SpinLock,0,sizeof(m_SpinLock));
	NdisAllocateSpinLock(&m_SpinLock);
	m_nValue = 0;
}

CMutex::~CMutex()
{
	NdisFreeSpinLock(&m_SpinLock);
}


int	CMutex::TryLock(void)
{
	int		ret=1;
	NdisAcquireSpinLock(&m_SpinLock);
	if(m_nValue)
		ret = 0;
	else
		m_nValue++;
	NdisReleaseSpinLock(&m_SpinLock);
	return ret;
}
	
int	CMutex::Lock(DWORD dwMicroSeconds, DWORD dwMicroPeriod)
{
	DWORD		dwRemains=dwMicroSeconds;
	DWORD		dwWaited;

	for(;!TryLock();dwRemains-=dwWaited)
	{
		if(!dwRemains) return 0;
		NdisMSleep((dwWaited=MINI(dwMicroPeriod,dwRemains))); // Min of uSecPeriod & uSecRemains
	}
	return 1;
}
	
void CMutex::Release(void)
{
	NdisAcquireSpinLock(&m_SpinLock);
	m_nValue = 0;
	NdisReleaseSpinLock(&m_SpinLock);
}

#else

CMutex::CMutex()
{
	memset((void*)&m_Critical,0,sizeof(m_Critical));
	InitializeCriticalSection(&m_Critical);

}

CMutex::~CMutex()
{
	DeleteCriticalSection(&m_Critical);
}


int	CMutex::TryLock(void)
{
	return TryEnterCriticalSection(&m_Critical);
}
	
int	CMutex::Lock(DWORD dwMicroSeconds, DWORD dwMicroPeriod)
{
	EnterCriticalSection(&m_Critical);
	return 1;
}
	
void CMutex::Release(void)
{
	LeaveCriticalSection(&m_Critical);
}

#endif