#ifndef __JLANG__JMUTEX__ #define __JLANG__JMUTEX__ #include /** * \file * Very basic lock facilities to be used in multithreaded programs. * \author cpellegrino */ namespace JSYNCHRONIZATION {} namespace JPP { using namespace JSYNCHRONIZATION; } namespace JSYNCHRONIZATION { /** * Scoped lock. * * The main purpose of this class is to provide an exception-safe locking * facility. * The lock on the mutex is acquired during construction, while the * unlock is performed in the destructor. * * Es: * Case 1, without scoped lock: * using namespace JSYNCHRONIZATION; * JMutex mutex; * * { * mutex.lock(); * throwing_function(variable_to_protect); // <- this shall throw * mutex.lock(); // <- this call is never * // executed -> deadlock * } * * Case 2, with scoped lock: * using namespace JSYNCHRONIZATION; * JMutex mutex; * * { * JScopedLock(mutex); * throwing_function(variable_to_protect); // <- this shall throw * } // the lock is released here automatically */ template class JBasicScopedLock { private: Lockable* m_lock; /** * Neither copy-constructible nor copy-assignable */ JBasicScopedLock(const JBasicScopedLock&); JBasicScopedLock(JBasicScopedLock&&); JBasicScopedLock operator =(const JBasicScopedLock&); JBasicScopedLock operator =(JBasicScopedLock&&); public: /** * Constructor * \param lock a lockable object (e.g.\ JScopedLock) */ explicit JBasicScopedLock(Lockable& lock) : m_lock(&lock) { m_lock->lock(); } /** * Destructor */ ~JBasicScopedLock() { unlock(); } /** * Unlock the mutex. * \return 0 on success, an error code otherwise. * See man 3p pthread_mutex_lock for further info. */ int unlock() { return m_lock->unlock(); } }; /** * Mutex. */ class JMutex { pthread_mutex_t m_mutex; public: /** * Constructor. */ JMutex() { pthread_mutex_init(&m_mutex, 0); } /** * Destructor. */ ~JMutex() { pthread_mutex_destroy(&m_mutex); } /** * Lock the mutex. * \return 0 on success, an error code otherwise. * See man 3p pthread_mutex_lock for further info. */ int lock() { return pthread_mutex_lock(&m_mutex); } /** * Try lock the mutex. * \return 0 on success, an error code otherwise. * See man 3p pthread_mutex_lock for further info. */ int try_lock() { return pthread_mutex_trylock(&m_mutex); } /** * Unlock the mutex. * \return 0 on success, an error code otherwise. * See man 3p pthread_mutex_lock for further info. */ int unlock() { return pthread_mutex_unlock(&m_mutex); } typedef JBasicScopedLock JScopedLock; }; } // ns JSYNCHRONIZATION #endif // __JLANG__JMUTEX__