91 lines
2.2 KiB
C++
91 lines
2.2 KiB
C++
/*! \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
|
||
PISpinlockLocker(PISpinlock & s, bool condition = true): spinlock(s), cond(condition) {if (cond) spinlock.lock();}
|
||
|
||
//! \~english Unlock "s" if "condition" was \c true
|
||
//! \~russian
|
||
~PISpinlockLocker() {if (cond) spinlock.unlock();}
|
||
|
||
private:
|
||
PISpinlock & spinlock;
|
||
bool cond;
|
||
|
||
};
|
||
|
||
|
||
#endif // PISPINLOCK_H
|