/*! \file pispinlock.h
 * \ingroup Thread
 * \~\brief
 * \~english Fast and full-load lock
 * \~russian Быстрая блокировка с полной нагрузкой
 */
/*
	PIP - Platform Independent Primitives
	PISpinlock
	Ivan Pelipenko peri4ko@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/>.
*/

#ifndef PISPINLOCK_H
#define PISPINLOCK_H

#include "piinit.h"
#include <atomic>


class PIP_EXPORT PISpinlock
{
public:
	NO_COPY_CLASS(PISpinlock);

	//! \~english Constructs unlocked spinlock
	//! \~russian Создает незаблокированный спинлок
	explicit PISpinlock() {flag.clear();}

	//! \~english Destroy spinlock
	//! \~russian Деструктор спинлока
	~PISpinlock() {}


	//! \~english Lock spinlock
	//! \~russian Блокирует спинлок
	//! \~\details
	//! \~english
	//! If spinlock is unlocked it set to locked state and returns immediate.
	//! If spinlock is already locked function blocks until spinlock will be unlocked
	//! \~russian
	//! Если спинлок свободен, то блокирует его и возвращает управление немедленно.
	//! Если спинлок заблокирован, то ожидает разблокировки, затем блокирует и возвращает управление
	void lock() {while (flag.test_and_set(std::memory_order_acquire));}

	//! \~english Unlock spinlock
	//! \~russian Разблокирует спинлок
	//! \~\details
	//! \~english
	//! In any case this function returns immediate
	//! \~russian
	//! В любом случае возвращает управление немедленно
	void unlock() {flag.clear(std::memory_order_release);}

private:
	std::atomic_flag flag;

};


class PIP_EXPORT PISpinlockLocker
{
public:
	NO_COPY_CLASS(PISpinlockLocker);

	//! \~english Constructs and lock "s" if "condition" is \c true
	//! \~russianСоздает и блокирует спинлок "m" если "condition" \c true
	PISpinlockLocker(PISpinlock & s, bool condition = true): spinlock(s), cond(condition) {if (cond) spinlock.lock();}

	//! \~english Unlock "s" if "condition" was \c true
	//! \~russian Разблокирует спинлок "m" если "condition" был \c true
	~PISpinlockLocker() {if (cond) spinlock.unlock();}

private:
	PISpinlock & spinlock;
	bool cond;

};


#endif // PISPINLOCK_H
