Producer-Consumer Problem

Download Report

Transcript Producer-Consumer Problem

Producer-Consumer Problem
Dr. Samir Tartir
Extracted from
Principles of Concurrent and Distributed Programming,
Second Edition
By M. Ben-Ari
Definitions
• Producers
– A producer process executes a statement produce to
create a data element and then sends this element to
the consumer processes.
• Consumers
– Upon receipt of a data element from the producer
processes, a consumer process executes a statement
consume with the data element as a parameter.
Examples
Producer
Consumer
Communications line
Web browser
Web browser
Communications line
Keyboard
Operating system
Word processor
Printer
Joystick
Game program
Game program
Display screen
Pilot controls
Control program
Control program
Aircraft control surfaces
Synchronization
• When a data element must be sent from
one process to another, the
communications can be synchronous ,that
is, communications cannot take place until
both the producer and the consumer are
ready to do so.
Asynchronous Communication
• More common, however, is asynchronous
communications in which the communications channel
itself has some capacity for storing data elements.
• This store, which is a queue of data elements, is called
a buffer.
• The producer executes an append operation to place a
data element on the tail of the queue,
• The consumer executes a take operation to remove a
data element from the head of the queue.
Issues
1. A consumer cannot take a data element from an
empty buffer
2. Since the size of any buffer is finite, a producer
cannot append a data element to a full buffer.
• Loss of data will occur when the producer tries
to append a data element to a full buffer; either
the operation will not succeed, in which case
that element is lost, or it will overwrite one of the
existing elements in the buffer.
Two Approaches
• Infinite buffers.
– the buffer is very large compared to the rate at
which data is produced, you can avoid the
extra overhead required by a finite buffer
algorithm, but risk an occasional loss of data.
• Finite (bounded) buffers.
– More realistic, and more work
Busy-Wait Semaphores
• A busy-wait semaphore does not have a
component S.L, so we will identify S with S.V.
The operations are defined as follows:
• wait(S)
– await S > 0
–S  S - 1
• signal(S)
–S
S + 1
Dining Philosophers
• The correctness properties are:
– A philosopher eats only if she has two forks.
– Mutual exclusion: no two philosophers may
hold the same fork simultaneously.
– Freedom from deadlock.
– Freedom from starvation.
– Efficient behavior in the absence of
contention.