Experiment Four producers and Consumers
First, the purpose of the experiment
1. Master the concept of critical areas and design principles of critical areas;
2. Grasp the concept of signal volume, the meaning of PV operation and the application of PV operation to realize the synchronization and mutual exclusion of the process;
3. Analyze the phenomenon of contention for resources, and learn how to resolve the process mutex.
Second, the contents and requirements of the experiment
Analysis of synchronization and mutual exclusion of process, programming to achieve classic process synchronization problem--the simulation of producer consumer problem
- Producer-Consumer problem statement:
There is an annular buffer pool that contains n buffers (0~n-1).
There are two types of processes: a set of producer processes and a set of consumer processes, the producer process puts products into an empty buffer, and the consumer process takes the product from the full buffer.
All processes must have mutually exclusive access to the buffer.
Producers cannot write data to full buffers, consumers cannot fetch data from an empty buffer, that is, producers and consumers must synchronize.
The process of allocating and releasing resources in a computer system: each process in a computer system can consume or produce a class of resources. When a process in a system uses a resource, it can be thought of as consumption, and the process is called a consumer. And when a process frees up resources, it is quite a producer.
- Define the data structures in the producer consumer problem and initialize them. Signal volume, initial value.
- Write the PV operation.
- Write the producer and consumer program, use the signal volume and its PV operation, realize the synchronization and mutual exclusion between producer and consumer.
- Simulation shows the effect of synchronization and mutual exclusion between producers and consumers.
Test methods, steps and Results
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 100
typedef struct PROCESS
{
int num;
}p;
P A[n];
int wordtime=0;
void Main () {
int i=0,j,run=1,n,p=0,v=0,num;
printf ("Input buffer size \ n");
scanf ("%d", &n);
while (run==1)
{
Srand (Time (NULL));
J=rand ()%2+1;
if (1==J)
{
if (i<5&&p==0&&v==0)
{
p++;
v++;
i++;
printf ("Production \ n");
p--;
v--;
}
else{
printf ("The warehouse is full cannot produce \ n");
}
}
Else
{
if (i>0&&p==0&&v==0)
{
p++;
v++;
i--;
printf ("Consumption \ n");
p--;
v--;
}
else{
printf ("No goods cannot be consumed \ n");
}
}
printf ("Whether to continue | | 1. is 2. No \ n ");
scanf ("%d", &run);
}
}
Test results:
Iv. Summary of the experiment
In this experiment, I learned a lot of things and successfully completed the experimental requirements.
Experiment four producers and consumers