Files
pip/libs/main/thread/pimutex.h
2026-03-12 14:46:57 +03:00

98 lines
3.1 KiB
C++

/*! \file pimutex.h
* \ingroup Thread
* \~\brief
* \~english Basic interthread lock
* \~russian Базовая межпоточная блокировка
*/
/*
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/>.
*/
#ifndef PIMUTEX_H
#define PIMUTEX_H
#include "piinit.h"
//! \~\ingroup Thread
//! \~\brief
//! \~english Mutex for mutual exclusion between threads.
//! \~russian Мьютекс для взаимоисключения между потоками.
class PIP_EXPORT PIMutex {
public:
NO_COPY_CLASS(PIMutex);
//! \~english Constructs unlocked mutex
//! \~russian Создает незаблокированный мьютекс
explicit PIMutex();
//! \~english Destroy mutex
//! \~russian Деструктор мьютекса
~PIMutex();
//! \~english Lock mutex
//! \~russian Блокирует мьютекс
void lock();
//! \~english Unlock mutex
//! \~russian Разблокирует мьютекс
void unlock();
//! \~english Try to lock mutex
//! \~russian Пробует заблокировать мьютекс
bool tryLock();
//! \~english Returns native mutex handle used by low-level synchronization code.
//! \~russian Возвращает нативный дескриптор мьютекса для низкоуровневой синхронизации.
void * handle();
private:
void init();
void destroy();
PRIVATE_DECLARATION(PIP_EXPORT)
};
//! \~\ingroup Thread
//! \~\brief
//! \~english Scope guard that locks a %PIMutex in constructor and unlocks it in destructor.
//! \~russian Защитник области видимости, который блокирует %PIMutex в конструкторе и разблокирует в деструкторе.
class PIP_EXPORT PIMutexLocker {
public:
NO_COPY_CLASS(PIMutexLocker);
//! \~english Constructs and lock "m" if "condition" is \c true
//! \~russian Создает и блокирует мьютекс "m" если "condition" \c true
PIMutexLocker(PIMutex & m, bool condition = true): mutex(m), cond(condition) {
if (cond) mutex.lock();
}
//! \~english Unlock "m" if "condition" was \c true
//! \~russian Разблокирует мьютекс "m" если "condition" был \c true
~PIMutexLocker() {
if (cond) mutex.unlock();
}
private:
PIMutex & mutex;
bool cond;
};
#endif // PIMUTEX_H