/* * UnlockGuard.h, part of VCMI engine * * Authors: listed in file AUTHORS in main folder * * License: GNU General Public License v2.0 or later * Full text of license available in license.txt file, in main folder * */ #pragma once VCMI_LIB_NAMESPACE_BEGIN namespace vstd { namespace detail { template class unlock_policy { protected: void unlock(Mutex &m) { m.unlock(); } void lock(Mutex &m) { m.lock(); } }; template class unlock_shared_policy { protected: void unlock(Mutex &m) { m.unlock_shared(); } void lock(Mutex &m) { m.lock_shared(); } }; } //similar to boost::lock_guard but UNlocks for the scope + assertions template > class unlock_guard : LockingPolicy { private: Mutex* m; explicit unlock_guard(unlock_guard&); unlock_guard& operator=(unlock_guard&); public: explicit unlock_guard(Mutex& m_): m(&m_) { this->unlock(*m); } unlock_guard() { m = nullptr; } unlock_guard(unlock_guard &&other) : m(other.m) { other.m = nullptr; } void release() { m = nullptr; } ~unlock_guard() { if(m) this->lock(*m); } }; template unlock_guard > makeUnlockGuard(Mutex &m_) { return unlock_guard >(m_); } template unlock_guard > makeEmptyGuard(Mutex &) { return unlock_guard >(); } template unlock_guard > makeUnlockGuardIf(Mutex &m_, bool shallUnlock) { return shallUnlock ? makeUnlockGuard(m_) : unlock_guard >(); } template unlock_guard > makeUnlockSharedGuard(Mutex &m_) { return unlock_guard >(m_); } template unlock_guard > makeUnlockSharedGuardIf(Mutex &m_, bool shallUnlock) { return shallUnlock ? makeUnlockSharedGuard(m_) : unlock_guard >(); } using unlock_shared_guard = unlock_guard>; } VCMI_LIB_NAMESPACE_END