In Qt documentation about QMutex it is said:
(…) 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(). A non-blocking alternative to lock() is tryLock(). (…)
I have been using this code many times:
QMutex mutex;<br>
while( !mutex.tryLock() );
Can someone explain me how this tryLock() method is built that while() loop won’t hang whole program?
Two threads shares one QMutex and act as a communication FIFO – when one thread is sending data, and another data is scheduled to the second thread, that thread is waiting for the first thread to complete. Communication comply with Modbus standard – send1-receive1, send2-receive2.
You cannot make parallel send and receive. So always one thread is active, the rest is waiting.
QMutex mutex;
thread1() {
while( !mutex.tryLock() )
;
doThread1Job();
}
thread2() {
while( !mutex.tryLock() )
;
doThread2Job();
}
If you’re spinning on
tryLock()in the GUI thread, then of course it will block your user interface. AtryLock()does not spin an event loop or anything like that. In your case, thetryLock()loop is same as just callinglock().The non-blocking alternative to
tryLock()should be used as follows: if it fails, you wait and try again. You set up asingleShotQTimer to fire your retry slot.In any case, it’d probably be easier to send a Qt signal to the waiting thread from the working thread, instead of implementing your own means of synchronization.