SLIDE 5 Producer/consumer: increased buffer capacity
1
T buf [ n ] # array , elements
type T
2
int f r o n t := 0 , r e a r := 0 ; # ‘ ‘ pointers ’ ’
3
sem empty := n ,
4
sem f u l l := 0 ;
1
process Producer {
2
while ( true ) {
3
P(empty ) ;
4
b u f f [ r e a r ] := data ;
5
r e a r := ( r e a r + 1) % n ;
6
V( f u l l ) ;
7
}
8
}
1
process Consumer {
2
while ( true ) {
3
P( f u l l ) ;
4
result := b u f f [ f r o n t ] ;
5
f r o n t := ( f r o n t + 1) % n
6
V(empty ) ;
7
}
8
}
several producers or consumers? Increasing the number of processes
- several producers and consumers.
- New synchronization problems:
– Avoid that two producers deposits to buf[rear] before rear is updated – Avoid that two consumers fetches from buf[front] before front is updated.
- Solution: additionally 2 binary semaphores for protection
– mutexDeposit to deny two producers to deposit to the buffer at the same time. – mutexFetch to deny two consumers to fetch from the buffer at the same time. Example: Producer/consumer with several processes
1
T buf [ n ] # array , elem ’ s
type T
2
int f r o n t := 0 , r e a r := 0 ; # ‘ ‘ pointers ’ ’
3
sem empty := n ,
4
sem f u l l := 0 ;
5
sem mutexDeposit , mutexFetch := 1 ; # protect the data s t u c t .
1
process Producer {
2
while ( true ) {
3
P(empty ) ;
4
P( mutexDeposit ) ;
5
b u f f [ r e a r ] := data ;
6
r e a r := ( r e a r + 1) % n ;
7
V( mutexDeposit ) ;
8
V( f u l l ) ;
9
}
10
}
1
process Consumer {
2
while ( true ) {
3
P( f u l l ) ;
4
P( mutexFetch ) ;
5
result := b u f f [ f r o n t ] ;
6
f r o n t := ( f r o n t + 1) % n
7
V( mutexFetch ) ;
8
V(empty ) ;
9
}
10
}
5