Prev | Current Page 280 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"

Programmers can use this mechanism to insure that one of two processes always executes first.
A semaphore also may be initialized to some number greater than 1, say 3. That would allow the first
three attempts to execute the P operation to succeed without blocking. To show how this might be useful, here
is an example of two cooperating programs where one produces a series of n items to be consumed by the other
(this is the ???producer??“consumer??? problem, much like the ???server thread??“worker thread??? example we discussed
earlier).
106 OPERATING SYSTEMS [CHAP. 6
// 'empty', 'full', and 'mutex' are all semaphore objects
empty = n // n = the maximum number of items
// permitted to be waiting to be consumed
full = 0
mutex = 1
/* Producer: */
while( true ) { // while( true ) means continue looping forever
. . .
produce an item
. . .
P(empty);
P(mutex);
. . .
send item to consumer
. . .
V(mutex);
V(full);
}
/* Consumer: */
while( true ) {
P( full )
P( mutex );
. . .
consume an item
. . .
V( mutex );
V( empty );
. . .
}
When the producer has an item ready to give to the consumer, the producer executes a P operation on the
empty semaphore. As long as there are fewer than the maximum permitted items waiting to be consumed, the
producer does not block.


Pages:
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
perfumy fm Anteny satelitarne apartamenty przy plaży online loan for bad credit rekuperatory