3.4.1 Shared-Memory Systems
- Processes use system calls to establish an area of shared-memory.
- Special provisions are necessary because normally it is a duty
of an OS to prevent user processes from accessing each other's
memory.
- Once two processes have done a certain amount of setup by using system
calls, they can communicate with reads and writes to memory, and without
any further need to make system calls.
- The producer-consumer pseudo-code illustrates one way that
a couple of processes can cooperate using communication with
shared memory.
--------------------------------
Producer-Consumer Problem Solution
Assumptions: Loads and Stores Are Atomic
--------------------------------
/* The following things are defined in memory
shared by the producer and consumer processes */
/* a constant denoting the buffer size */
#define BUFFER_SIZE 10
/* a data type to be used as the buffer item */
typedef struct
(
/* Appropriate fields to be contained in
an item are defined here. */
) item ;
/* declaration of an array of items */
item buffer [BUFFER_SIZE] ;
/* the location into which the producer
will place its next item */
int in = 0 ;
/* the location from which the consumer
will take its next item */
int out = 0 ;
--------------------------------
(producer code)
while (true)
{
/* call to local function and
use of local variable */
nextProduced = makeItem() ;
/* while buffer full */
while ( ( (in+1) % BUFFER_SIZE ) == out )
/* do nothing */ ;
buffer[in] = nextProduced ;
in = (in+1) % BUFFER_SIZE ;
}
--------------------------------
(consumer code)
while (true)
{
/* while buffer empty */
while ( in == out )
/* do nothing */ ;
/* store buffer[out] into a local variable */
nextConsumed = buffer[out] ;
out = (out+1) % BUFFER_SIZE ;
/* call local function */
consume(nextConsumed) ;
}
--------------------------------