1 // Copyright 2010 Jochen Becher
3 // This file is part of MovieSchedule.
5 // MovieSchedule is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // MovieSchedule is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with MovieSchedule. If not, see <http://www.gnu.org/licenses/>.
18 #include "assertedlock.h"
20 #include <QMutexLocker>
23 AssertedLock::AssertedLock()
29 _lock(QReadWriteLock::Recursive)
33 AssertedLock::~AssertedLock()
36 QMutexLocker locker(&_mutex);
37 Q_ASSERT_X(_lock_counter == 0, __func__, "lock counter must be 0");
41 void AssertedLock::Lock(LockMode mode)
45 QMutexLocker locker(&_mutex);
46 if (GetLockCounter() > 0) {
47 if (GetLockMode() == READ) {
49 Q_ASSERT_X(mode == READ, __func__, "unable to change lockmode from READ to WRITE");
69 void AssertedLock::Unlock()
73 QMutexLocker locker(&_mutex);
74 Q_ASSERT_X(GetLockCounter() > 0, __func__, "too many unlocks");
82 AssertedLock::LockMode AssertedLock::GetLockMode() const
84 return _thread_data[QThread::currentThread()]._lock_mode;
87 void AssertedLock::SetLockMode(LockMode mode)
89 _thread_data[QThread::currentThread()]._lock_mode = mode;
92 int AssertedLock::GetLockCounter() const
94 return _thread_data[QThread::currentThread()]._lock_counter;
97 void AssertedLock::IncLockCounter()
99 _thread_data[QThread::currentThread()]._lock_counter += 1;
103 void AssertedLock::DecLockCounter()
105 _thread_data[QThread::currentThread()]._lock_counter -= 1;
109 void AssertedLock::AssertLockedForMode(LockMode mode) const
111 QMutexLocker locker(&_mutex);
112 if (GetLockCounter() <= 0) {
113 Q_ASSERT_X(_lock_counter > 0, __func__, "expected lock");
115 if (GetLockMode() == READ) {
117 Q_ASSERT_X(mode == READ, __func__, "locked for READ but WRITE lock expected");
122 void AssertedLock::AssertNotLocked() const
124 QMutexLocker locker(&_mutex);
125 Q_ASSERT_X(GetLockCounter() == 0, __func__, "unexpected lock.");