[Qt-interest] Error in QWaitCondition example or am I missing something?

Christopher Dyken erikd at ifi.uio.no
Fri Aug 21 10:01:48 CEST 2009


Hi,

In the 4.6-20090821 documentation of QWaitCondition, there is an
example on a producer-consumer pattern using one producer and three
consumers. As I understand the text, the example shows how to
guarantee that all three consumer threads are woken on a key-press.

The example is as follows:

// consumer thread
 forever {
     mutex.lock();
     keyPressed.wait(&mutex);
     ++count;
     mutex.unlock();

     do_something();

     mutex.lock();
     --count;
     mutex.unlock();
 }

// producer thread
 forever {
     getchar();

     mutex.lock();
     // Sleep until there are no busy worker threads
     while (count > 0) {
         mutex.unlock();
         sleep(1);
         mutex.lock();
     }
     keyPressed.wakeAll();
     mutex.unlock();
 }

The "count" variable makes sure that all consumers are finished
processing before the next character is processed.

Consider the following scheduling scenario:

1 producer thread - fetch a char, lock mutex, count ==0, wake all
waiting threads (which is zero), unlock mutex, scheduled out at end of
iteration
2 consumer thread 0 - lock mutex, unlock and wait
3 consumer thread 1 - lock mutex, unlock and wait
4 consumer thread 2 - lock mutex, unlock and wait
5 producer thread - fetch the second char, lock mutex, count == 0,
wake all waiting threads (which is three), unlock mutex
6 consumer thread 0 - woken, process the second char of input,
scheduled out at end of iteration
7 consumer thread 1 - woken, process the second char of input,
scheduled out at end of iteration
8 consumer thread 1 - woken, process the second char of input,
scheduled out at end of iteration
9 producer thread - fetch the third char, count == 0, wake all waiting
threads (which is zero)

and so on. As I see it, only every other char is processed in this
case. The problem is that if a wake-call is issued between the
consumers unlock the mutex after --count; and before the lock on mutex
before keyPressed.wait, the consumer will miss out on that iteration.

At least this is how I see it. Maybe am I missing something here?

Cheers,
Chris



More information about the Qt-interest-old mailing list