Lecture 2
Lecture 2
out in
A Correct
Solution to the
Infinite-Buffer
Producer/Cons
umer Problem
Using Binary
Semaphores
/* pr ogr am producerconsumer */
semaphore n = 0, s = 1;
voi d producer()
Figure 5.11 {
whi l e (true) {
produce();
A Solution semWait(s);
append();
to the semSignal(s);
Infinite- semSignal(n);
Buffer }
}
Producer/C voi d consumer()
onsumer {
whi l e (true) {
Problem semWait(n);
Using semWait(s);
Semaphores take();
semSignal(s);
consume();
}
}
voi d main()
{
par begi n (producer, consumer);
}
b[1] b[2] b[3] b[4] b[5] b[n]
out in
(a)
in out
(b)
A Solution to
the Bounded-
Buffer
Producer/Cons
umer Problem
Using
Semaphores
Implementation of
Semaphores
Imperativethat the semWait and
semSignal operations be implemented as
atomic primitives
Can be implemented in hardware or firmware
Software schemes such as Dekker’s or
Peterson’s algorithms can be used
Useone of the hardware-supported
schemes for mutual exclusion
Figure 5.14
Two Possible Implementations of Semaphores
semWait(s) semWait(s)
{ {
whi l e ( compare_and_swap(s.flag, 0 , 1) == 1) inhibit interrupts;
/* do nothing */; s.count--;
s.count--; i f (s.count < 0) {
i f (s.count < 0) { /* place this process in s.queue */;
/* place this process in s.queue*/; /* block this process and allow interrupts */;
/* block this process (must also set s.flag to 0) }
*/; el se
} allow interrupts;
s.flag = 0; }
}
semSignal(s)
semSignal(s) {
{ inhibit interrupts;
whi l e ( compare_and_swap(s.flag, 0 , 1) == 1) s.count++;
/* do nothing */; i f (s.count <= 0) {
s.count++; /* remove a process P from s.queue */;
i f (s.count <= 0) { /* place process P on ready list */;
/* remove a process P from s.queue */; }
/* place process P on ready list */; allow interrupts;
} }
s.flag = 0;
}