14 Condition Variable
14 Condition Variable
Condition Variables
Reading materials: Chap.30
1
Pusan National University
Condition Variables
■ There are many cases where a thread wishes to check
whether a condition is true before continuing its execution.
■ Example:
▪ A parent thread might wish to check whether a child thread has
completed.
▪ This is often called a join().
2
Pusan National University
3
Pusan National University
▪ This is hugely inefficient as the parent spins and wastes CPU time.
4
Pusan National University
5
Pusan National University
7
Pusan National University
8
Pusan National University
10
Pusan National University
11
Pusan National University
■ Consumer
▪ Grab data items out of the buffer consume them in some way
13
Pusan National University
Bounded buffer
■ A bounded buffer is used when you pipe the output of one
program into another.
▪ Example: grep foo file.txt | wc –l
▪The grep process is the producer.
▪ The wc process is the consumer.
▪ Between them is an in-kernel bounded buffer.
▪ Bounded buffer is Shared resource → Synchronized access is required.
14
Pusan National University
15
Pusan National University
▪ Producer puts an integer into the shared buffer loops number of times.
▪ Consumer gets the data out of that shared buffer.
16
Pusan National University
17
Pusan National University
18
Pusan National University
19
Pusan National University
▪ There is no guarantee that when the woken thread runs, the state will
still be as desired → Mesa semantics.
▪ Virtually every system ever built employs Mesa semantics.
20
Pusan National University
21
Pusan National University
22
Pusan National University
23
Pusan National University
24
Pusan National University
25
Pusan National University
26
Pusan National University
28
Pusan National University
29
Pusan National University
Covering Conditions
■ Assume there are zero bytes free
▪ Thread 𝑇𝑎 calls allocate(100).
▪ Thread 𝑇𝑏 calls allocate(10).
▪ Both 𝑇𝑎 and 𝑇𝑏 wait on the condition and go to sleep.
▪ Thread 𝑇𝑐 calls free(50).
30
Pusan National University
31
Pusan National University
32
Pusan National University
Next Class..
■ Dijkstra and colleagues invented the semaphore as a single
primitive for all things related to synchronization; as you will
see, one can use semaphores as both locks and condition
variables.
33