0% found this document useful (0 votes)
5 views33 pages

Os Lab

Uploaded by

Aman Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views33 pages

Os Lab

Uploaded by

Aman Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Galgotias College of

Engineering and Technology


Galgotias College of
Engineering and Technology
Session: 2021-22

Operating Systems Lab


[KCS451]
[Link] [CSE-(AI)]
Semester : IV

Submitted To: Submitted By:

Ms. Ruchika Sharma Tushar Agrawal


Assistant Professor Roll no.- 2000971520060
CSE-(AI)
INDEX

[Link]. Program Date Signature

Study of hardware and software requirements of different


1 operating systems (UNIX, LINUX, WINDOWS XP,
WINDOWS 7/8)

Execute various UNIX system calls for


(i) Process Management
2
(ii) File Management
(iii) Input/Output System calls

Implement CPU Scheduling Policies:


3 (i) SJF (ii) Priority (iii) FCFS (iv) Multi-level Queue

Implement File Storage Allocation Techniques:


4 (i) Continuous (ii) Linked-list (iii) Indirect Allocation

Implementation of contiguous allocation techniques:


5 (i) Worst-Fit (ii) Best-Fit (iii) First-Fit

Calculation of External and Internal fragmentation:


6 (i) Free space list of blocks from system
(ii) List process file from the system

Implementation of compaction for the continually


7 changing memory layout and calculate total movement of
data

Implementation of Resource Allocation Graph (RAG)


8

Implementation of Banker’s Algorithm


9

Conversion of resource allocation graph (RAG) to wait for


10 graph (WFG) for each type of method used for storing
graph

Implement the solution for Bounded Buffer


11 (producer-consumer) problem using inter process
communication techniques- Semaphores

Implement the solutions for Readers-Writers problem


12 using inter process communication technique- Semaphore
INTRODUCTION
OPERATING SYSTEM:

HISTORY OF OS:
The operating system is a system program that serves as an interface between the
computing system and the end-user. Operating systems create an environment where
the user can run any programs or communicate with software or applications in a
comfortable and well-organised way. Furthermore, an operating system is a software
program that manages and controls the execution of application programs, software
resources and computer hardware. It also helps manage the software/hardware
resources, such as file management, memory management, input/ output and many
peripheral devices like a disk drive, printers, etc. These are the popular operating
systems: Linux OS, Windows OS, Mac OS, VMS, OS/400 etc.

It was in 1956 when the first operating system was introduced. It was introduced in
order to make the IBM mainframe computer run. It was introduced by General
Motors. Later on, other owners of IBM Mainframe Computer followed a similar
pattern for making the operating system for their computer system. If we look at the
computer systems from different generations, then they have been classified into 4
generations according to their architecture. But you should also know that the
architecture of these computers is also related to the operating systems. Like the 1st
Generation Computers which were introduced in the year 1940, they did not have any
operating systems. No one even thought of an operating system or would have heard
about it. The digital computers at that time worked with the help of the programs only
like we have mentioned above. There were no programming languages also at that
time. Then in the 2nd Generation, in the 1950s some improvement was brought and it
was the time when the first operating systems were introduced, about which we have
mentioned above. It was introduced for IBM 701. At that time there was the
single-stream batch processing system. It was because the users used to submit data
and programs in the batches or the groups. In the 3rd Generation, in the 1960s, some
advanced technologies were developed. The multiprogramming concept was
introduced by the operating system designers in the 1960s. There were many new
techniques which were introduced in the operating system. Due to the
multiprogramming concept, several jobs were done at the same time. When a job was
waiting for the Input-Output Operation, at the same time the CPU was used by
another job, unlike the old operating system without the multiprogramming feature.
The operating systems in the 3rd generation were made in such a way that all the
programs can run at a fast speed and can get completed fast. It also made the other
programs initiate and start soon which are waiting to run. The time-sharing feature
was also introduced in the 3rd generation operating system. To multi-program the
interactive users in large numbers, the time-sharing technique was made. In the 4th
Generation, the operating systems were used in personal computers also. This was
made possible by the Large-Scale Integration Circuits Development. Some of the
operating systems which were used at that time are, UNIX and MS-DOS. At present,
there are many operating systems which are in use like Linux and Microsoft
Windows. For mobile phones also, we have operating systems like Android and IOS.
At present, most of us are using the Windows Operating System, which was
introduced in the year 1985. There are different types of operating systems which are
being used these days like Batch Operating System, Real-Time Operating System,
Multiprocessing Operating System, Multitasking /Time Sharing Operating System,
Network Operating System, and Mobile Operating System.

ARCHITECTURE OF OS :
PROGRAM - 1

Objective:

Study of Hardware and Software requirements of different Operating Systems(UNIX


, LINUX, Windows XP, WINDOWS 7/8)

Theory:

The most common set of requirements defined by any Operating System or Software
application is the physical computer resources, also known as hardware. A hardware
requirements list is often accompanied by a hardware compatibility list (HCL),
especially in the case of Operating Systems.

Hardware and Software minimum Requirements:

1. Windows 7/8
Windows 8 is a version of the Microsoft Windows operating system released on
October 26,2012. It was the first major update to windows . Since Windows 7, which
was released over three years earlier. While Windows 7 offered several performance
improvements over Windows Vista , there were few changes to the look and feel of
the operating system.
Its requirements are as follows:
● Processor: 1GHz (Gigahertz) or faster processor or SoC.
● RAM: 1GB (GigaByte) for 32-bit or 2GB (GigaByte) for 64-bit.
● Hard Disk Space: 16GB for 32-bit Operating System or 20GB for 64-bit
Operating System.
● Graphics Card: Direct X 9 or later with WDDM 1.0 driver.
● Display: 800 x 6009 with WDDM driver.

2. Windows XP

Windows XP is an operating system produced by Microsoft as part of the Windows


NT family of operating systems. It was the successor to both Windows 2000 for
professional users and Windows Me for home users. As such, Windows XP was the
first consumer edition of Windows not to be based on MS-DOS.
The minimum hardware requirements for Windows XP Home Edition are:
● Pentium 233-megahertz (MHz) processor or faster (300 MHz is recommended)
● At least 64 megabytes (MB) of RAM (128 MB is recommended)
● At least 1.5 gigabytes (GB) of available space on the hard disk
● CD-ROM or DVD-ROM drive
● Keyboard and a Microsoft Mouse or some other compatible pointing device
● Video adapter and monitor with Super VGA (800 x 600)or higher resolution
● Sound card
● Speakers or headphones

3. UNIX Operating System


UNIX is a multi-user operating system. Developed at AT & T Bell Industries,
USA in 1969. Ken Thomson along with Dennis Ritchie developed it from MULTICS
(Multiplexed Information and Computing Service) OS. By 1980, UNIX had been
completely rewritten using C [Link] systems also have a graphical user
interface(GUI) similar to Microsoft Windows which provides an easy to use
environment. However knowledge of Unix is required for operations which aren’t
covered by a graphical program , or for when there is no windows interface available
, for example, in a telnet session.
Its requirements are as follows:
● RAM: 1 GB
● Processor: IBM 604e processor with a clock speed of 375 MHz or faster
● Free disk space: /tmp must have 1 GB free disk space. If Tivoli Identity
Manager install WebSphere Application Server, (WAS_HOME} must have 800
MB free disk space and /var must have 300 MB free disk space. Allocate 500
MB for /itim45.
4. LINUX Operating System
LINUX is similar to UNIX, which was created by Linus Torualds. All UNIX
commands work in Linux. Linux is an open source software. The main feature of
Linux is coexisting with other OS such as windows and UNIX. It is an open source
and community developed operating system for computers, servers, mainframes,
mobile devices and embedded devices. It is supported on almost every major
computer platform including X86, ARM and SPARC, making it one of the most
widely supported operating systems.
Its requirements are as follows:
● 32-bit Intel-compatible processor running at 2 GHz or greater.
● 512 MB RAM Disk space: 2.5 GB for Pipeline Pilot server plus components.
● A DVD-ROM drive.
● TCP/IP Network Interface
● IBM AIX 4.3.3
● Sun Solaris 2.7 or 2.8
PROGRAM - 2

Objective:

Execute various UNIX system calls for


(i) Process Management
(ii) File Management
(iii) Input/Output System Calls

Theory:
The interface between a process and an operating system is provided by system calls.
In general, system calls are available as assembly language instructions. They are
also included in the manuals used by the assembly level programmers.
Unix System Calls:
System calls in Unix are used for file system control, process control, interprocess
communication etc. Access to the Unix kernel is only available through these system
calls. Generally, system calls are similar to function calls, the only difference is that
they remove the control from the user process.
There are around 80 system calls in the Unix interface currently. Details about some
of the important ones are given as follows:

System Call Description


access( ) This checks if a calling process has access to the required
file
chdir( ) This command changes the directory of the system
chmod( ) The mode of a file can be changed using this command
chown( ) This changes the ownership of a particular file
kill ( ) This call sends kill signal to one or more processes
link( ) A new file name is linked to an existing file using link
system call
open( ) This opens a file for the reading or writing process
pause( ) The pause call suspends a file until a particular signal
occurs
stime( ) This system call sets the current time
times( ) Gets the parent and child process times
alarm( ) The alarm system call sets the alarm clock of a process
fork( ) A new process is created using this command
chroot( ) This changes the root directory of a file
exit( ) This system call is used to exit a process
bg To send a process to the background
fg To run a stopped process in the foreground
top It gives the details on all active processes
ps Gives the status of processes running for a user
ps PID Gives the status of a particular process
pidof Gives the process ID(PID) of a process
nice Starts a process with a given priority
renice Changes priority of an already running process
df Gives free hard disk space on your system
free Gives the free RAM on your system
pwd Refers to the present working directory in which you are
operating
dir Prints (on the terminal) all the available directories in the
present working directory
ls Lists down all the directories and files inside the present
working directory (Gives the path of a specific directory)
cd Changes the directories in the terminal
touch Creates a new file as well one can change the timestamp
of any file
cat Shows the content of any file
mkdir Creates a new directory in pwd
rm Removes the specific file from a directory
cp Copies any file or folder to any directory
mv Moves files around the computer, and also rename files
or directories inside a specific directory
head Gives the first ten lines of a text file
tail Gives the last ten lines of the text file
wget Downloads the content from the internet
ping Checks the connectivity to the server
w Displays the user details that are currently logged into the
system
cal Shows the calender of the present month
time Shows the current time
hostname Gives the name of the host at the terminal
man Gives the complete user manual of a particular command
grep Searches for a pattern in which a specific word lies
history Shows the list of commands that have been executed
-apt Install or remove packages, or performs the other
maintenance tasks
uname Gives the release number and the version of the
UBUNTU
zip Converts the files to zip archive
passwd Changes the password of the Ubuntu user
PROGRAM - 3

Objective:

Write a program to implement the following CPU Scheduling Policies:


I. SJF
II. Priority
III. FCFS
IV. Multi-level Queue

I. SJF [Shortest Job First]

Theory:

Shortest Job First (SJF) is an algorithm in which the process having the smallest
execution time is chosen for the next execution. This scheduling method can be
preemptive or non-preemptive. It significantly reduces the average waiting time for
other processes awaiting execution. The full form of SJF is Shortest Job First.
Some of the characteristics of Shortest Job First(SJF) scheduling algorithm are as
follows:
● It is associated with each job as a unit of time to complete.
● This algorithm method is helpful for batch-type processing, where waiting for
jobs to complete is not critical.
● It can improve process throughput by making sure that shorter jobs are
executed first, hence possibly having a short turnaround time.
● It improves job output by offering shorter jobs, which should be executed first,
which mostly have a shorter turnaround time.

C Program for SJF Scheduling Algorithm:


#include<stdio.h>
void main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);

printf("\nEnter Burst Time:\n");


for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1; //contains process number
}

//sorting burst time in ascending order using selection sort


for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting time for first process will be zero

//calculate waiting time


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=(float)total/n; //average waiting time


total=0;

printf("\n Process\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total += tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=(float)total/n; //average turnaround time


printf("\n\n Average Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

OUTPUT:
II. Priority Scheduling

Theory:

Priority Scheduling is a method of scheduling processes that is based on priority. In


this algorithm, the scheduler selects the tasks to work as per the priority. The
processes with higher priority should be carried out first, whereas jobs with equal
priorities are carried out on a round-robin or FCFS basis. Priority depends upon
memory requirements, time requirements, etc.
Some of the characteristics of Priority scheduling algorithm are as follows:
● A CPU algorithm that schedules processes based on priority.
● It is used in Operating systems for performing batch processes.
● If two jobs having the same priority are Ready, it works on a First Come, First
Serve basis.
● In priority scheduling, a number is assigned to each process that indicates its
priority level.
● Lower the number, higher is the priority.
● In this type of scheduling algorithm, if a newer process arrives, that is having a
higher priority than the currently running process, then the currently running
process is preempted.

C Program for Priority based Scheduling Algorithm:


#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);
printf("\nEnter Burst Time and Priority\n");
for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1; //contains process number
}

//sorting burst time, priority and process number in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}
temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0; //waiting time for first process is zero
//calculate waiting time
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total += wt[i];
}
avg_wt = total/n; //average waiting time
total=0;
printf("\n Process \t Burst Time \tWaiting Time\tTurnaround Time");
for(i=0;i<n;i++)
{
Tat[i] = bt[i]+wt[i]; //calculate turnaround time
total += tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=total/n; //average turnaround time
printf("\n\n Average Waiting Time=%d",avg_wt);
printf("\nAverage Turnaround Time=%d\n",avg_tat);
return 0;
}
OUTPUT:

III. FCFS [First Come First Serve]

Theory:

First Come First Serve (FCFS) is an operating system scheduling algorithm that
automatically executes queued requests and processes in order of their arrival. It is
the easiest and simplest CPU scheduling algorithm. In this type of algorithm,
processes which request the CPU first get the CPU allocation first. This is managed
with a FIFO queue. The full form of FCFS is First Come First Serve. As the process
enters the ready queue, its PCB (Process Control Block) is linked with the tail of the
queue and, when the CPU becomes free, it should be assigned to the process at the
beginning of the queue.
Some of the characteristics of the FCFS scheduling method are as follows:
● It supports non-preemptive and preemptive scheduling algorithms.
● Jobs are always executed on a first-come, first-serve basis.
● It is easy to implement and use.
● This method is poor in performance, and the general wait time is quite high.

C Program for FCFS Scheduling Algorithm:


#include<stdio.h>
int main()
{
int AT[10],BT[10],WT[10],TT[10],n;
int burst=0,cmpl_T;
float Avg_WT,Avg_TT,Total=0;
printf("Enter number of the process\n");
scanf("%d",&n);
printf("Enter Arrival time and Burst time of the process\n");
printf("AT\tBT\n");
for(int i=0;i<n;i++)
{
scanf("%d%d",&AT[i],&BT[i]);
}
// Logic for calculating Waiting time
for(int i=0;i<n;i++)
{
if(i==0)
WT[i]=AT[i];
else
WT[i]=burst-AT[i];
burst+=BT[i];
Total+=WT[i];
}
Avg_WT=Total/n;
// Logic for calculating Turnaround time
cmpl_T=0;
Total=0;
for(int i=0;i<n;i++)
{
cmpl_T+=BT[i];
TT[i]=cmpl_T-AT[i];
Total+=TT[i];
}
Avg_TT=Total/n;
// printing of outputs
printf("Process ,Waiting_time ,TurnA_time\n");
for(int i=0;i<n;i++)
{
printf("%d\t\t%d\t\t%d\n",i+1,WT[i],TT[i]);
}
printf("Average waiting time is : %f\n",Avg_WT);
printf("Average turnaround time is : %f\n",Avg_TT);
return 0;
}

OUTPUT:
IV. Multilevel Queue Scheduling

Theory:

Multi Level Queue Scheduling algorithm separates the ready queue into various
separate queues. In this method, processes are assigned to a queue based on a specific
property of the process, like the process priority, size of the memory, etc. However,
this is not an independent scheduling OS algorithm as it needs to use other types of
algorithms in order to schedule the jobs.
Some of the characteristics of the Multi Level Queue Scheduling method are as
follows:
● Multiple queues should be maintained for processes with some characteristics.
● Every queue may have its separate scheduling algorithms.
● Priorities are given for each queue.

C Program for Multilevel Queue Scheduling Algorithm:


#include<stdio.h>
int main()
{
int p[20],bt[20], su[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
printf("Enter the number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time of Process%d:", i);
scanf("%d",&bt[i]);
printf("System/User Process (0/1) ? ");
scanf("%d", &su[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(su[i] > su[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=su[i];
su[i]=su[k];
su[k]=temp;
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\t SYSTEM/USER PROCESS \tBURST TIME\tWAITING
TIME\tTURNAROUND TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],su[i],bt[i],wt[i],tat[i]);
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
return 0;
}

OUTPUT:
PROGRAM - 9
Objective:

Write a program in C programming language to implement Banker's Algorithm.

Theory:

The banker’s algorithm is a resource allocation and deadlock avoidance algorithm


that tests for safety by simulating the allocation for predetermined maximum possible
amounts of all resources, then makes an “s-state” check to test for possible activities,
before deciding whether allocation should be allowed to continue.
Following Data structures are used to implement the Banker’s Algorithm:
Let ‘n’ be the number of processes in the system and ‘m’ be the number of resource
types.

Available:

● It is a 1-d array of size ‘m’ indicating the number of available resources of each
type.
● Available[ j ] = k means there are ‘k’ instances of resource type Rj.

Max:

● It is a 2-d array of size ‘n*m’ that defines the maximum demand of each
process in a system.
● Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource
type Rj.

Allocation:

● It is a 2-d array of size ‘n*m’ that defines the number of resources of each type
currently allocated to each process.
● Allocation[ i, j ] = k means process Pi is currently allocated ‘k’ instances of
resource type Rj.
Need:

● It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of
each process..
● Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource type
Rj.
● Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]

C Program for Banker’s Algorithm:


#include <stdio.h>

int current[5][5], maximum_claim[5][5], available[5];


int allocation[5] = {0, 0, 0, 0, 0};
int maxres[5], running[5], safe = 0;
int counter = 0, i, j, exec, resources, processes, k = 1;

int main()
{
printf("\nEnter number of processes: ");
scanf("%d", &processes);

for (i = 0; i < processes; i++)


{
running[i] = 1;
counter++;
}

printf("\nEnter number of resources: ");


scanf("%d", &resources);

printf("\nEnter Claim Vector:");


for (i = 0; i < resources; i++)
{
scanf("%d", &maxres[i]);
}

printf("\nEnter Allocated Resource Table:\n");


for (i = 0; i < processes; i++)
{
for(j = 0; j < resources; j++)
{
scanf("%d", &current[i][j]);
}
}
printf("\nEnter Maximum Claim Table:\n");
for (i = 0; i < processes; i++)
{
for(j = 0; j < resources; j++)
{
scanf("%d", &maximum_claim[i][j]);
}
}

printf("\nThe Claim Vector is: ");


for (i = 0; i < resources; i++)
{
printf("\t%d", maxres[i]);
}

printf("\nThe Allocated Resource Table:\n");


for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
printf("\t%d", current[i][j]);
}
printf("\n");
}

printf("\nThe Maximum Claim Table:\n");


for (i = 0; i < processes; i++)
{
for (j = 0; j < resources; j++)
{
printf("\t%d", maximum_claim[i][j]);
}
printf("\n");
}

for (i = 0; i < processes; i++)


{
for (j = 0; j < resources; j++)
{
allocation[j] += current[i][j];
}
}

printf("\nAllocated resources:");
for (i = 0; i < resources; i++)
{
printf("\t%d", allocation[i]);
}

for (i = 0; i < resources; i++)


{
available[i] = maxres[i] - allocation[i];
}

printf("\nAvailable resources:");
for (i = 0; i < resources; i++)
{
printf("\t%d", available[i]);
}
printf("\n");

while (counter != 0)
{
safe = 0;
for (i = 0; i < processes; i++)
{
if (running[i])
{
exec = 1;
for (j = 0; j < resources; j++)
{
if (maximum_claim[i][j] - current[i][j] > available[j])
{
exec = 0;
break;
}
}
if (exec)
{
printf("\nProcess%d is executing\n", i + 1);
running[i] = 0;
counter--;
safe = 1;

for (j = 0; j < resources; j++)


{
available[j] += current[i][j];
}
break;
}
}
}
if (!safe)
{
printf("\nThe processes are in unsafe state.\n");
break;
}
else
{
printf("\nThe process is in safe state");
printf("\nAvailable vector:");

for (i = 0; i < resources; i++)


{
printf("\t%d", available[i]);
}

printf("\n");
}
}
return 0;
}

OUTPUT:
PROGRAM - 11

Objective:

Write a program in C programming language to implement the solution for Bounded


Buffer (Producer - Consumer) problem using Inter Process Communication
Techniques- Semaphores.

Theory:

The Producer-Consumer problem is a classical multi-process synchronisation


problem, that is we are trying to achieve synchronisation between more than one
process. There is one Producer in the producer-consumer problem, Producer is
producing some items, whereas there is one Consumer that is consuming the items
produced by the Producer. The same memory buffer is shared by both producers and
consumers which is of fixed-size. The task of the Producer is to produce the item, put
it into the memory buffer, and again start producing items. Whereas the task of the
Consumer is to consume the item from the memory buffer.

Problem: Given the common fixed-size buffer, the task is to make sure that the
producer can’t add data into the buffer when it is full and the consumer can’t remove
data from an empty buffer.

Solution: The producer is to either go to sleep or discard data if the buffer is full. The
next time the consumer removes an item from the buffer, it notifies the producer, who
starts to fill the buffer again. In the same manner, the consumer can go to sleep if it
finds the buffer to be empty. The next time the producer puts data into the buffer, it
wakes up the sleeping consumer.

Approach: The idea is to use the concept of parallel programming and Critical
Section to implement the Producer-Consumer problem in C language.
C Program for Bounded Buffer (Producer - Consumer) problem’s
Solution:

#include<stdio.h>
#include<stdlib.h>

int mutex=1,full=0,empty=3,x=0;

int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\[Link]\[Link]\[Link]");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}

return 0;
}

int wait(int s)
{
return (--s);
}

int signal(int s)
{
return(++s);
}

void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}

void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}

OUTPUT:
PROGRAM - 12

Objective:

Write a program in C programming language to implement the solutions for


Readers-Writers problem using Inter Process Communication Technique-
Semaphores.

Theory:

The readers-writers problem relates to an object such as a file that is shared


between multiple processes. Some of these processes are readers i.e. they only
want to read the data from the object and some of the processes are writers i.e.
they want to write into the object. The readers-writers problem is used to
manage synchronisation so that there are no problems with the object data. For
example - If two readers access the object at the same time there is no problem.
However if two writers or a reader and writer access the object at the same time,
there may be problems. To solve this situation, a writer should get exclusive
access to an object i.e. when a writer is accessing the object, no reader or writer
may access it. However, multiple readers can access the object at the same time.

C Program for Readers - Writers problem’s Solution:


#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;
void *writer(void *wno)
{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);
sem_post(&wrt);
}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);

// Reader acquire the lock before modifying numreader


pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
sem_post(&wrt); // If this is the last reader, it will wake up the writer.
}
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);
int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering producer and consumer
for(int i = 0; i < 10; i++) {
pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for(int i = 0; i < 5; i++) {
pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i]);
}

for(int i = 0; i < 10; i++) {


pthread_join(read[i], NULL);
}
for(int i = 0; i < 5; i++) {
pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}
OUTPUT:

You might also like