QWaitCondition Class Reference

The QWaitCondition class provides a condition variable for synchronizing threads. More...

 #include <QWaitCondition>

Note: All functions in this class are thread-safe.

Public Functions

QWaitCondition ()
~QWaitCondition ()
bool wait ( QMutex * mutex, unsigned long time = ULONG_MAX )
bool wait ( QReadWriteLock * readWriteLock, unsigned long time = ULONG_MAX )
void wakeAll ()
void wakeOne ()

Detailed Description

The QWaitCondition class provides a condition variable for synchronizing threads.

QWaitCondition allows a thread to tell other threads that some sort of condition has been met. One or many threads can block waiting for a QWaitCondition to set a condition with wakeOne() or wakeAll(). Use wakeOne() to wake one randomly selected condition or wakeAll() to wake them all.

For example, let's suppose that we have three tasks that should be performed whenever the user presses a key. Each task could be split into a thread, each of which would have a run() body like this:

 forever {
     mutex.lock();
     keyPressed.wait(&mutex);
     do_something();
     mutex.unlock();
 }

Here, the keyPressed variable is a global variable of type QWaitCondition.

A fourth thread would read key presses and wake the other three threads up every time it receives one, like this:

 forever {
     getchar();
     keyPressed.wakeAll();
 }

The order in which the three threads are woken up is undefined. Also, if some of the threads are still in do_something() when the key is pressed, they won't be woken up (since they're not waiting on the condition variable) and so the task will not be performed for that key press. This issue can be solved using a counter and a QMutex to guard it. For example, here's the new code for the worker threads:

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

     do_something();

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

Here's the code for the fourth 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 mutex is necessary because the results of two threads attempting to change the value of the same variable simultaneously are unpredictable.

Wait conditions are a powerful thread synchronization primitive. The Wait Conditions example shows how to use QWaitCondition as an alternative to QSemaphore for controlling access to a circular buffer shared by a producer thread and a consumer thread.

See also QMutex, QSemaphore, QThread, and Wait Conditions Example.

Member Function Documentation

QWaitCondition::QWaitCondition ()

Constructs a new wait condition object.

QWaitCondition::~QWaitCondition ()

Destroys the wait condition object.

bool QWaitCondition::wait ( QMutex * mutex, unsigned long time = ULONG_MAX )

Releases the locked mutex and waits on the wait condition. The mutex must be initially locked by the calling thread. If mutex is not in a locked state, this function returns immediately. If mutex is a recursive mutex, this function returns immediately. The mutex will be unlocked, and the calling thread will block until either of these conditions is met:

  • Another thread signals it using wakeOne() or wakeAll(). This function will return true in this case.
  • time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the event must be signalled). This function will return false if the wait timed out.

The mutex will be returned to the same locked state. This function is provided to allow the atomic transition from the locked state to the wait state.

See also wakeOne() and wakeAll().

bool QWaitCondition::wait ( QReadWriteLock * readWriteLock, unsigned long time = ULONG_MAX )

Releases the locked readWriteLock and waits on the wait condition. The readWriteLock must be initially locked by the calling thread. If readWriteLock is not in a locked state, this function returns immediately. The readWriteLock must not be locked recursively, otherwise this function will not release the lock properly. The readWriteLock will be unlocked, and the calling thread will block until either of these conditions is met:

  • Another thread signals it using wakeOne() or wakeAll(). This function will return true in this case.
  • time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the event must be signalled). This function will return false if the wait timed out.

The readWriteLock will be returned to the same locked state. This function is provided to allow the atomic transition from the locked state to the wait state.

This function was introduced in Qt 4.4.

See also wakeOne() and wakeAll().

void QWaitCondition::wakeAll ()

Wakes all threads waiting on the wait condition. The order in which the threads are woken up depends on the operating system's scheduling policies and cannot be controlled or predicted.

See also wakeOne().

void QWaitCondition::wakeOne ()

Wakes one thread waiting on the wait condition. The thread that is woken up depends on the operating system's scheduling policies, and cannot be controlled or predicted.

If you want to wake up a specific thread, the solution is typically to use different wait conditions and have different threads wait on different conditions.

See also wakeAll().

Notes provided by the Qt Community
Informative
  • 0

Votes: 0

Coverage: Qt library 4.7, Qt 4.8

Picture of Diluka Diluka

Hobby Entomologist
23 notes

Wait Conditions Example

Wait Conditions Example

  1. Global Variables
  2.  
  3.  const int DataSize = 100000;
  4.  const int BufferSize = 8192;
  5.  char buffer[BufferSize];
  6.  
  7.  QWaitCondition bufferNotEmpty;
  8.  QWaitCondition bufferNotFull;
  9.  QMutex mutex;
  10.  int numUsedBytes = 0;
  11.  
  12. //////////////////////////////////////////////////////////////////////
  13.  
  14. Producer Class
  15.  
  16. class Producer : public QThread
  17.  {
  18.  public:
  19.      void run();
  20.  };
  21.  
  22.  void Producer::run()
  23.  {
  24.      qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
  25.  
  26.      for (int i = 0; i < DataSize; ++i) {
  27.          mutex.lock();
  28.          if (numUsedBytes == BufferSize)
  29.              bufferNotFull.wait(&mutex);
  30.          mutex.unlock();
  31.  
  32.          buffer[i % BufferSize] = "ACGT"[(int)qrand() % 4];
  33.  
  34.          mutex.lock();
  35.          ++numUsedBytes;
  36.          bufferNotEmpty.wakeAll();
  37.          mutex.unlock();
  38.      }
  39.  }
  40. //////////////////////////////////////////////////////////////////////////////
  41. Consumer Class
  42.  
  43. class Consumer : public QThread
  44.  {
  45.  public:
  46.      void run();
  47.  };
  48.  
  49.  void Consumer::run()
  50.  {
  51.      for (int i = 0; i < DataSize; ++i) {
  52.          mutex.lock();
  53.          if (numUsedBytes == 0)
  54.              bufferNotEmpty.wait(&mutex);
  55.          mutex.unlock();
  56.  
  57.          fprintf(stderr, "%c", buffer[i % BufferSize]);
  58.  
  59.          mutex.lock();
  60.          --numUsedBytes;
  61.          bufferNotFull.wakeAll();
  62.          mutex.unlock();
  63.      }
  64.      fprintf(stderr, "\n");
  65.  }
  66. /////////////////////////////////////////////////////////////////////////////////////
  67.  
  68. The main() Function
  69.  
  70. int main(int argc, char *argv[])
  71.  {
  72.      QCoreApplication app(argc, argv);
  73.      Producer producer;
  74.      Consumer consumer;
  75.      producer.start();
  76.      consumer.start();
  77.      producer.wait();
  78.      consumer.wait();
  79.      return 0;
  80.  }

(Reference: trinitydesktop.org)

[Revisions]