/*
    PIP - Platform Independent Primitives
    PIMutex, PIMutexLocker
    Ivan Pelipenko peri4ko@yandex.ru, Stephan Fomenko, Andrey Bychkov work.a.b@yandex.ru

    This program 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 3 of the License, or
    (at your option) any later version.

    This program 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 program.  If not, see <http://www.gnu.org/licenses/>.
*/

//! \addtogroup Thread
//! \{
//! \class PIMutex pimutex.h
//!
//! \~\brief
//! \~english Simple mutex
//! \~russian Простой мьютекс
//!
//!
//! \~\details
//! \~english \section PIMutex_sec0 Synopsis
//! \~russian \section PIMutex_sec0 Краткий обзор
//!
//! \~english
//! %PIMutex provides critical code section defence between several threads.
//! Using mutex guarantees execution of some code only one of threads.
//! Mutex contains logic state and functions to change it: \a lock(),
//! \a unlock() and \a tryLock().
//!
//! For automatic lock-unlock use \a PIMutexLocker.
//!
//! \~russian
//! %PIMutex предоставляет межпотоковую защиту критических секций кода.
//! Использование мьютекса гарантирует выполнение секции только один потоком.
//! Мьютекс состоит из логического состояния и методов для его изменения:
//! \a lock(), \a unlock() and \a tryLock().
//!
//! Для автоматической блокировки-разблокировки используйте \a PIMutexLocker.
//!
//! \~english \section PIMutex_sec1 Usage
//! \~russian \section PIMutex_sec1 Использование
//!
//! \~english
//! Block of code that should to be executed only one thread simultaniously
//! should to be started with \a lock() and finished with \a unlock().
//!
//! \~russian
//! Части кода, которые должны быть выполнены только одним потоком в любой момент
//! времени должны начинаться с вызова \a lock() и заканчиваться вызовом \a unlock().
//!
//! \~\code
//! // critical section start
//! mutex.lock();
//! // ... your code here
//! mutex.unlock();
//! // critical section end
//! \endcode
//! \}


//! \addtogroup Thread
//! \{
//! \class PIMutexLocker pimutex.h
//!
//! \~\brief
//! \~english %PIMutex autolocker
//! \~russian Автоблокировщик %PIMutex
//!
//!
//! \~\details
//!
//! \~english
//! When a %PIMutexLocker object is created, it attempts to lock the mutex it is given, if "condition" \c true.
//! When control leaves the scope in which the %PIMutexLocker object was created,
//! the %PIMutexLocker is destructed and the mutex is released, if "condition" was \c true.
//!
//! If "condition" \c false this class do nothing.
//!
//! The %PIMutexLocker class is non-copyable.
//!
//! \~russian
//! При создании экземпляра %PIMutexLocker блокируется переданный мьютекс, если "condition" \c true.
//! Когда выполнение покидает область жизни объекта, вызывается его деструктор и мьютекс
//! разблокируется, если "condition" был \c true.
//!
//! Если "condition" \c false, то этот объект ничего не делает.
//!
//! Класс %PIMutexLocker некопируемый.
//!
//! \~\code
//! // critical section start
//! {
//! PIMutexLocker locker(mutex);
//! // ... your code here
//! }
//! // critical section end
//! \endcode
//! \}


#include "pimutex.h"

#include "piincludes_p.h"
#if defined(WINDOWS)
#  include <synchapi.h>
#elif defined(FREERTOS)
#  include <semphr.h>
#else
#  include <pthread.h>
#endif


PRIVATE_DEFINITION_START(PIMutex)
#if defined(WINDOWS)
	CRITICAL_SECTION
#elif defined(FREERTOS)
	SemaphoreHandle_t
#else
	pthread_mutex_t
#endif
	mutex;
PRIVATE_DEFINITION_END(PIMutex)


PIMutex::PIMutex() {
	init();
}


PIMutex::~PIMutex() {
	destroy();
}


//! \~\details
//! \~english
//! If mutex is unlocked it set to locked state and returns immediate.
//! If mutex is already locked function blocks until mutex will be unlocked
//! \~russian
//! Если мьютекс свободен, то блокирует его и возвращает управление немедленно.
//! Если мьютекс заблокирован, то ожидает разблокировки, затем блокирует и возвращает управление
void PIMutex::lock() {
#if defined(WINDOWS)
	EnterCriticalSection(&(PRIVATE->mutex));
#elif defined(FREERTOS)
	xSemaphoreTake(PRIVATE->mutex, portMAX_DELAY);
#else
	pthread_mutex_lock(&(PRIVATE->mutex));
#endif
}


//! \~\details
//! \~english
//! In any case this function returns immediate
//! \~russian
//! В любом случае возвращает управление немедленно
void PIMutex::unlock() {
#if defined(WINDOWS)
	LeaveCriticalSection(&(PRIVATE->mutex));
#elif defined(FREERTOS)
	xSemaphoreGive(PRIVATE->mutex);
#else
	pthread_mutex_unlock(&(PRIVATE->mutex));
#endif
}


//! \~\details
//! \~english
//! If mutex is unlocked it set to locked state and returns "true" immediate.
//! If mutex is already locked function returns immediate an returns "false"
//! \~russian
bool PIMutex::tryLock() {
	bool ret =
#if defined(WINDOWS)
		(TryEnterCriticalSection(&(PRIVATE->mutex)) != 0);
#elif defined(FREERTOS)
		xSemaphoreTake(PRIVATE->mutex, 0);
#else
		(pthread_mutex_trylock(&(PRIVATE->mutex)) == 0);
#endif
	return ret;
}


void * PIMutex::handle() {
#ifdef FREERTOS
	return PRIVATE->mutex;
#else
	return (void *)&(PRIVATE->mutex);
#endif
}


void PIMutex::init() {
#if defined(WINDOWS)
	InitializeCriticalSection(&(PRIVATE->mutex));
#elif defined(FREERTOS)
	PRIVATE->mutex = xSemaphoreCreateMutex();
#else
	pthread_mutexattr_t attr;
	piZeroMemory(attr);
	pthread_mutexattr_init(&attr);
	pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
	piZeroMemory(PRIVATE->mutex);
	pthread_mutex_init(&(PRIVATE->mutex), &attr);
	pthread_mutexattr_destroy(&attr);
#endif
}


void PIMutex::destroy() {
#if defined(WINDOWS)
	DeleteCriticalSection(&(PRIVATE->mutex));
#elif defined(FREERTOS)
	vSemaphoreDelete(PRIVATE->mutex);
#else
	pthread_mutex_destroy(&(PRIVATE->mutex));
#endif
}
