Docsity

conditional variables, Lecture notes of Operating Systems

Partial preview of the text

Download conditional variables and more Lecture notes Operating Systems in PDF only on Docsity!

Condition Variables

Md Ahsanul Kabir

Another type of sychronization

  • Locks allow one type of synchronization between threads – mutual exclusion
  • Another common requirement in multi-threaded applications – waiting and signaling - E.g., Thread T1 wants to continue only after T2 has finished some task
  • Can accomplish this by busy-waiting on some variable, but inefficient
  • Need a new synchronization primitive: condition variables

Example: parent waits for child

Why check condition in while loop?

  • In the example code, why do we check condition before calling wait? - In case the child has already run and done is true, then no need to wait
  • Why check condition with “while” loop and not “if”?
    • To avoid corner cases of thread being woken up even when condition not true (may be an issue with some implementations)

Example: Producer/Consumer problem

  • A common pattern in multi-threaded programs
  • Example: in a multi-threaded web server, one thread accepts requests from the network and puts them in a queue. Worker threads get requests from this queue and process them.
  • Setup: one or more producer threads, one or more consumer threads, a shared buffer of bounded size

Producer/Consumer with 2 CVs