Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fixed|libcore|Lockable: Issue with the mutex lock counter
When unlocking a Lockable, it was first unlocked and only then its
lock count was decremented. This meant that execution may have
continued elsewhere with an incorrect lock count. Now the lock count
is manipulated only while the Lockable still remains locked.

However, keeping track of the lock count is only relevant in debug
builds, so the counting is now ifdef'ed away in release builds. This
means individual (un)lockings are faster as one doesn't have to lock
and unlock the lock count mutex.
  • Loading branch information
skyjake committed Oct 22, 2014
1 parent a5937cb commit d97cbbb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
4 changes: 4 additions & 0 deletions doomsday/libcore/include/de/concurrency/lockable.h
Expand Up @@ -47,14 +47,18 @@ class DENG2_PUBLIC Lockable
/// Release the lock.
void unlock() const;

#ifdef DENG2_DEBUG
/// Returns true, if the lock is currently locked.
bool isLocked() const;
#endif

private:
mutable QMutex _mutex;

#ifdef DENG2_DEBUG
mutable int _lockCount;
mutable QMutex _countMutex;
#endif
};

} // namespace de
Expand Down
25 changes: 17 additions & 8 deletions doomsday/libcore/src/concurrency/lockable.cpp
Expand Up @@ -25,7 +25,9 @@ namespace de {

Lockable::Lockable()
: _mutex(QMutex::Recursive)
#ifdef DENG2_DEBUG
, _lockCount(0)
#endif
{}

Lockable::~Lockable()
Expand All @@ -35,32 +37,39 @@ Lockable::~Lockable()

void Lockable::lock() const
{
_mutex.lock();

#ifdef DENG2_DEBUG
_countMutex.lock();
_lockCount++;
_countMutex.unlock();

_mutex.lock();
#endif
}

void Lockable::unlock() const
{
// Release the lock.
_mutex.unlock();

#ifdef DENG2_DEBUG
_countMutex.lock();
_lockCount--;
_countMutex.unlock();
#endif

// Release the lock.
_mutex.unlock();

#ifdef DENG2_DEBUG
DENG2_ASSERT(_lockCount >= 0);
_countMutex.unlock();
#endif
}

#ifdef DENG2_DEBUG
bool Lockable::isLocked() const
{
bool result;
_countMutex.lock();
result = (_lockCount > 0);
bool result = (_lockCount > 0);
_countMutex.unlock();
return result;
}
#endif

} // namespace de

0 comments on commit d97cbbb

Please sign in to comment.