1 /******************************************************************************* 2 ** 3 ** Photivo 4 ** 5 ** Copyright (C) 2013 Michael Munzert <mail@mm-log.com> 6 ** Copyright (C) 2013 Bernd Schoeler <brjohn@brother-john.net> 7 ** 8 ** This file is part of Photivo. 9 ** 10 ** Photivo is free software: you can redistribute it and/or modify 11 ** it under the terms of the GNU General Public License version 3 12 ** as published by the Free Software Foundation. 13 ** 14 ** Photivo is distributed in the hope that it will be useful, 15 ** but WITHOUT ANY WARRANTY; without even the implied warranty of 16 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 ** GNU General Public License for more details. 18 ** 19 ** You should have received a copy of the GNU General Public License 20 ** along with Photivo. If not, see <http://www.gnu.org/licenses/>. 21 ** 22 *******************************************************************************/ 23 24 #include "ptMutexLocker.h" 25 #include <stdexcept> 26 27 /*! 28 Creates a ptMutexLocker object and locks AMutex. If the lock cannot be acquired after 29 ATimeoutMsec throws a std::runtime_error exception. 30 */ ptMutexLocker(QMutex * AMutex,int ATimeoutMsec)31ptMutexLocker::ptMutexLocker(QMutex* AMutex, int ATimeoutMsec): 32 FMutex(AMutex), 33 FTimeout(ATimeoutMsec), 34 FUnlocked(false) 35 { 36 this->lock(); 37 } 38 39 /*! Destroys a ptMutexLocker object and releases the lock if necessary. */ ~ptMutexLocker()40ptMutexLocker::~ptMutexLocker() { 41 this->unlock(); 42 } 43 44 /*! 45 Re-acquires the lock after a call to unlock(). If the lock cannot be acquired after the 46 timeout defined in the ctor throws a std::runtime_error exception. 47 Does nothing if unlock() was not called previously. 48 */ relock()49void ptMutexLocker::relock() { 50 if (FUnlocked){ 51 this->lock(); 52 FUnlocked = false; 53 } 54 } 55 56 /*! Releases the lock. Consecutive calls to unlock() are allowed. */ unlock()57void ptMutexLocker::unlock() { 58 if (!FUnlocked) { 59 FMutex->unlock(); 60 FUnlocked = true; 61 } 62 } 63 lock()64void ptMutexLocker::lock() { 65 if (!FMutex->tryLock(FTimeout)) { 66 throw std::runtime_error("ptMutexLocker: Failed to acquire lock."); 67 } 68 } 69