yan bellavance
yan bellavance

Reputation: 4830

QMutex stuck in locked state

I have a function which is part of a class and in this function there is a mutex.lock at the beginning of the function and a mutex.unlock just before its return. Now I have encountered a situation where the mutex is stuck in the locked state. What could be doing this if this function is the only place where I use that mutex to lock and unlock. The function is called from the main thread and from 1 or 2 other QThreads.

UPDATE: the problem was due to the thread not sleeping in between function calls. Maybe the lack of a sleep relocked the mutex really fast? You could also call yieldCurrentThread();

Upvotes: 3

Views: 3885

Answers (4)

Miguel Sevilla
Miguel Sevilla

Reputation: 466

My guess is that one of the other threads that calls this function is still holding the lock, and has not released it, so the next thread that tries to enter that section of code, has to wait until the lock is releasd.

Are there any blocking calls inside the lock/unlock code?

From the Qt QMutex Documentation:

When you call lock() in a thread, other threads that try to call lock() in the same place will block until the thread that got the lock calls unlock()

Upvotes: 0

sth
sth

Reputation: 229613

If an exception is thrown in the function the unlock() at the end might not get executed. To make sure the QMutex gets unlocked in such cases you can do the locking with a QMutexLocker object. This object will automatically unlock the mutex when it get's destroyed, even if that happens during stack unwinding after an exception.

Upvotes: 5

George Yohng
George Yohng

Reputation: 11

On Mac OS X I had QMutex hangs even in a 100% correct logic. I made a wrapper call around QMutex, which increased/decreased an atomic reference count, and QMutex was hanging at a place, where the reference count was signifying no held mutex.

This has happened to me once in Qt3, and once more in the recent Qt (4.6.2 or 4.7.0, I don't remember). Replacing QMutex with a custom class, that goes directly to OS primitives - solved the problem.

Note however, this problem only occurred on OS X in my case. On Windows the same code was working perfectly.

Upvotes: 1

yan bellavance
yan bellavance

Reputation: 4830

The mutex was relocking right after unlocking from the same QThread so fast that the main thread didn't have time to lock it back. Adding a sleep or yieldCurrentThread() fixed the problem

Upvotes: 0

Related Questions