views:

86

answers:

2

In Qt, I have a method which contains a mutex lock and unlock. The problem is when the mutex is unlock it sometimes take long before the other thread gets the lock back. In other words it seems the same thread can get the lock back(method called in a loop) even though another thread is waiting for it. What can I do about this? One thread is a qthread and the other thread is the main thread.

A: 

It shouldn't be possible to release a lock and then get it back if some other thread is already waiting on it.

Check that you actually releasing the lock when you think you do. Check that waiting thread actually waits (and not spins a loop with a trylock tests and sleeps, I actually done that once and was very puzzled at first :)).

Or if waiting thread really never gets time to even reach locking code, try QThread::yieldCurrentThread(). This will stop current thread and give scheduler a chance to give execution to somebody else. Might cause unnecessary switching depending on tightness of your loop.

Eugene
It's completely possible. It all depends on details of the scheduler. Releasing a lock does not necessarily wake the other thread. If your thread keeps running and your ask for the lock again before the other thread wakes up, you'll the lock again.
R Samuel Klatchko
Agree with Sam. It is totally dependant on the priority of the blocked and running processes. The only way to give control back to another process at specific execution point is to sleep or yield if the waiting process is a lower priority.
Casey
Yeah, wasn't really thinking :)
Eugene
been there done that, it really does relock multiple times even with yieldToThread(). With a very small sleep in the threads loop ie 1us the other thread can almost never get the lock. With a big sleep then you can have the other thread take hold of mutex but this is not desired specially if you cant afford to sleep that long. With no sleep forget it.
yan bellavance
+3  A: 

You can have your thread that just unlocked the mutex relinquish the processor. On Posix, you do that by calling pthread_yield() and on Windows by calling Sleep(0).

That said, there is no guarantee that the thread waiting on the lock will be scheduled before your thread wakes up again.

R Samuel Klatchko
Isn't this OS dependant, especially scheduler has a almighty influence on that. So this is actually implementation/OS dependant. Correct me if I am wrong.
penguinpower
@soxs060389 - yes, that is OS dependent. That's why I wrote "there is no guarantee..."
R Samuel Klatchko