/*  $Id: mutex_pthread.cpp,v 1.10 2003/09/05 20:33:06 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
**
*/
#ifndef __USE_UNIX98
	#define __USE_UNIX98
#endif  

#include "Core/precomp.h"
#include "API/Core/System/cl_assert.h"
#include <pthread.h>
#include "mutex_pthread.h"

// We need to do this because the posix threads library under linux obviously
// suck:
extern "C"
{
#ifdef __FreeBSD__
	int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int kind);
#else
	int pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr, int kind);
#endif
}

CL_Mutex *CL_Mutex::create()
{
	return new CL_Mutex;
}
////////////////////////////////////////////////////////////////////////////////
// CL_Mutex Posix implementation

CL_Mutex::CL_Mutex()
: impl(new CL_Mutex_Generic)
{
	pthread_mutexattr_t attr;
	pthread_mutexattr_init(&attr);

// No PTHREAD_MUTEX_RECURSIVE_NP under MaxOSX
// Why I must define PTHREAD_MUTEX_RECURSIVE_NP is a riddle
// maybe below code is wrong?
#ifdef __APPLE__
#  define PTHREAD_MUTEX_RECURSIVE_NP
#endif

#ifdef PTHREAD_MUTEX_RECURSIVE_NP
// FreeBSD & cygwin
	pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE);
#else
	pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
#endif
	pthread_mutex_init(&impl->mutex, &attr);
	pthread_mutexattr_destroy(&attr);

	pthread_cond_init(&impl->cond,0);
}

CL_Mutex::CL_Mutex(const CL_Mutex &copy)
{
	cl_assert(false);
}

void CL_Mutex::operator=(const CL_Mutex &copy)
{
	cl_assert(false);
}

CL_Mutex::~CL_Mutex()
{
	pthread_mutex_destroy(&impl->mutex);
	pthread_cond_destroy(&impl->cond);
	delete impl;
}
	
void CL_Mutex::enter()
{
	pthread_mutex_lock(&impl->mutex);
}

void CL_Mutex::leave()
{
	pthread_mutex_unlock(&impl->mutex);
}


void CL_Mutex::wait()
{
	pthread_cond_wait(&impl->cond,&impl->mutex);
}


void CL_Mutex::notify()
{
	pthread_cond_signal(&impl->cond);
}

void CL_Mutex::notify_all()
{
	pthread_cond_broadcast(&impl->cond);
}
