#include <../arch/arch.h>

#ifdef	ARCH_THREADING_SUPPORTED

vboolean V_CALL
archCreateMutex(arch_mutex_p mutex_ret)
{
#ifdef	CONFIG_NT_ONLY
	InitializeCriticalSection(&mutex_ret->cs);
	mutex_ret->lock_count = 0;
#else
	mutex_ret->mutex = CreateMutex(NULL,FALSE,NULL);
#endif
	return true;
}

vboolean V_CALL
archDestroyMutex(arch_mutex_p mutex)
{
	/*
	 * First of all, release all waiting threads; it probably cause
	 * core dump, but deadlock is worse. In either case, presence of
	 * waiting threads at the time of mutexDestroy() means broken code.
	 */
#ifdef	CONFIG_NT_ONLY
	while(mutex->lock_count--)
		LeaveCriticalSection(&mutex->cs);
	DeleteCriticalSection(&mutex->cs);
#else	/* !CONFIG_NT_ONLY */
	while(ReleaseMutex(mutex->mutex));
	CloseHandle(mutex->mutex);
#endif	/* !CONFIG_NT_ONLY */
	return true;
}

vboolean V_CALL
archTryLockMutex(arch_mutex_p mutex)
{
#ifdef	CONFIG_NT_ONLY
	if(TryEnterCriticalSection(&mutex->cs))
	{
		mutex->lock_count++;
		return true;
	}
	else
		return false;
#else	/* !CONFIG_NT_ONLY */
	if(WaitForSingleObject(mutex->mutex,0) == WAIT_OBJECT_0)
		return true;
	else
		return false;
#endif	/* !CONFIG_NT_ONLY */
}

vboolean V_CALL
archLockMutex(arch_mutex_p mutex)
{
#ifdef	CONFIG_NT_ONLY
	EnterCriticalSection(&mutex->cs);
	mutex->lock_count++;
	return true;
#else	/* !CONFIG_NT_ONLY */
	if(WaitForSingleObject(mutex->mutex,INFINITE) == WAIT_OBJECT_0)
		return true;
	else
		return false;
#endif	/* !CONFIG_NT_ONLY */
}

vboolean V_CALL
archUnlockMutex(arch_mutex_p mutex)
{
#ifdef	CONFIG_NT_ONLY
	if(!mutex->lock_count)
		return false;
	mutex->lock_count--;
	LeaveCriticalSection(&mutex->cs);
	return true;
#else	/* !CONFIG_NT_ONLY */
	return ReleaseMutex(mutex->mutex) ? true : false;
#endif	/* !CONFIG_NT_ONLY */
}

#endif	/* ARCH_THREADING_SUPPORTED */
