/***************************************************************************
                          cmutex.cpp  -  mutex
                             -------------------
    begin                : Sun Sep 30 2001
    copyright            : (C) 2001-2004 by Mathias Küster
    email                : mathen@users.berlios.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "cmutex.h"

#ifndef WIN32
#include <stdio.h>
#include <string.h>
#endif

/** */
CMutex::CMutex()
{
#ifdef WIN32
	InitializeCriticalSection(&m_CS);
#else
	int i;

	if ( (i=pthread_mutex_init(&mutex,NULL)) == 0 )
	{
		m_bMutexInit = true;
	}
	else
	{
		m_bMutexInit = false;
		
		printf("pthread_mutex_init: %s\n",strerror(i));
	}
#endif
}

/** */
CMutex::~CMutex()
{
#ifdef WIN32
	DeleteCriticalSection(&m_CS);
#else
	int i;

	if ( m_bMutexInit )
	{
		if ( (i=pthread_mutex_destroy(&mutex)) != 0 )
		{
			printf("pthread_mutex_destroy: %s\n",strerror(i));
		}
	}
	
	m_bMutexInit = false;

#endif
}

/** */
int CMutex::Lock()
{
#ifdef WIN32
	EnterCriticalSection(&m_CS);
	return 0;
#else
	int i = -1;
	
	if ( m_bMutexInit )
	{
		if ( (i=pthread_mutex_lock(&mutex)) != 0 )
		{
			printf("pthread_mutex_lock: %s\n",strerror(i));
		}
	}

	return i;
#endif
}

/** */
bool CMutex::TryLock()
{
#ifdef WIN32
	return (TryEnterCriticalSection(&m_CS) != 0);
#else
	if ( m_bMutexInit )
		return ( pthread_mutex_trylock(&mutex) == 0 );
	return false;
#endif
}

/** */
int CMutex::UnLock()
{
#ifdef WIN32
	LeaveCriticalSection(&m_CS);
	return 0;
#else
	int i = -1;

	if ( m_bMutexInit )
	{
		if ( (i=pthread_mutex_unlock(&mutex)) != 0 )
		{
			printf("pthread_mutex_unlock: %s\n",strerror(i));
		}
	}

	return i;
#endif
}
