[Qt-interest] QWaitCondition wakeOne/wakeAll

Bradley T. Hughes bradley.hughes at nokia.com
Wed Jun 10 10:48:08 CEST 2009


Lars Amsel wrote:
> Hi,
> 
> I have a question regarding QWaitCondition. The documentation states, that waiting for a condition ensure atomic transition from locked state to wait state.
> 
> What about the wakeOne(), wakeAll()? Is the transition from wait state to the locked state atomic too?

Yes, it is. But not that neither wakeOne() nor wakeAll() have any knowledge 
of the mutex you are waiting on.

> Somewhere in the code I have
> 
>  1:  mutex.lock();
>  2:  waitCondition(&mutex);
>  3:  processSomething();
>  4:  msg = NULL;
>  5:  mutex.unlock();
> 
> in another thread I do
> 
>  6:  waitCondition.wakeOne();

You have a race here. There are several things that can happen here:

1. the other thread may not be waiting yet (so the wakeOne() is essentially 
lost)
2. the other thread may not wake up quickly enough if it is waiting (and the 
lock you have below will effectively block it from waking up).

>  7:  mutex.lock();
>  8:  if (msg != NULL) {
>  9:    doDefaultProcessing();
> 10:  }
> 11:  mutex.unlock();
> 
> Under rare conditions it occurs that msg is not NULL in line 8,
> especially when first and second call are close together. The only
> explanation I haveis that the wakeOne() does not ensure that the mutex is
> locked afterreturning from that call.

Right. Like I pointed out above, wakeOne() and wakeAll() know nothing about 
your mutex. To fix the race you have above, you need to move the wakeOne() 
to after the lock() call.

> How do I solve that? I thought about a second wait condition to wait for
> processSomething(). The problem there is, that the second code snippet could
> be executed without the first ever called. The wait for processSomething()
> would then wait eternally.

It's kind of unclear what you are wanting to accomplish, so I can only guess 
what it is you are wanting to solve. Perhaps you could explain a bit more 
what you are trying to do?

-- 
Bradley T. Hughes (Nokia-D-Qt/Oslo), bradley.hughes at nokia.com
Sandakervn. 116, P.O. Box 4332 Nydalen, 0402 Oslo, Norway



More information about the Qt-interest-old mailing list