CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Condition variables

Condition variables provide another way for threads to synchronize. While mutexes implement synchronization by controlling thread access to data, condition variables allow threads to synchronize based upon the actual value of data.

Without condition variables, we would require threads to continually poll (possibly in a critical section), to check if a condition is met - very resource intensive! A condition variable helps avoid the polling.

A condition variable is always used in conjunction with a mutex lock.
Consider this sequence in which threadB informs threadA when a required condition is met:

main thread:

  • declare and initialize global variables requiring synchronization
  • declare and initialize a condition variable object
  • declare and initialize an associated mutex
  • create threads A and B to execute in parallel
threadA:
  • execute to the point where a certain condition must occur
    (a variable reaches a required value)
  • lock associated mutex and check value of a global variable
  • call pthread_cond_wait() to perform a blocking wait for signal from threadB. The call to pthread_cond_wait() automatically and atomically unlocks the associated mutex variable so that it can be used by threadB
  • when signalled, wake up; mutex is automatically and atomically locked
  • explicitly unlock mutex
  • continue execution
threadB:
  • execute
  • lock associated mutex
  • update the value of the global variable that threadA is waiting on
  • check value of the global threadA wait variable - if it fulfills the desired condition, signal threadA
  • unlock mutex
  • continue execution.
main thread:
  • join threadA or threadB, or continue execution...

 


CITS2002 Systems Programming, Lecture 21, p5, 10th October 2023.