How non-blocking loop {while( QMutex::trylock() );} works?

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() )

thread2() { 
    while( !mutex.tryLock() )


If you're spinning on tryLock() in the GUI thread, then of course it will block your user interface. A tryLock() does not spin an event loop or anything like that. In your case, the tryLock() loop is same as just calling lock().

The non-blocking alternative to tryLock() should be used as follows: if it fails, you wait and try again. You set up a singleShot QTimer 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.

Need Your Help

Trying to suppress StyleCop message SA1513:ClosingCurlyBracketMustBeFollowedByBlankLine

c# stylecop

I am trying to suppress the following StyleCop message for a specific property:

How do I focus a foreign window?

c# .net focus

I have an application which may only have one instance of itself open at a time. To enforce this, I use this code: