0% found this document useful (0 votes)
48 views48 pages

C Programs for Bankers and Dining Philosophers

Uploaded by

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

C Programs for Bankers and Dining Philosophers

Uploaded by

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

/* Bankers Algorithm using C*/

#include <stdio.h>
#include <conio.h>
void main() {
int k=0,a=0,b=0,instance[5],availability[5],allocated[10][5],need[10][5],MAX[10]
[5],process,P[10],no_of_resources, cnt=0,i, j;
printf("\n Enter the number of resources : ");
scanf("%d", &no_of_resources);
printf("\n enter the max instances of each resources\n");
for (i=0;i<no_of_resources;i++) {
availability[i]=0;
printf("%c= ",(i+97));
scanf("%d",&instance[i]);
}
printf("\n Enter the number of processes : ");
scanf("%d", &process);
printf("\n Enter the allocation matrix \n ");
for (i=0;i<no_of_resources;i++)
printf(" %c",(i+97));
printf("\n");
for (i=0;i <process;i++) {
P[i]=i;
printf("P[%d] ",P[i]);
for (j=0;j<no_of_resources;j++) {
scanf("%d",&allocated[i][j]);
availability[j]+=allocated[i][j];
}
}
printf("\nEnter the MAX matrix \n ");
for (i=0;i<no_of_resources;i++) {
printf(" %c",(i+97));
availability[i]=instance[i]-availability[i];
}
printf("\n");
for (i=0;i <process;i++) {
printf("P[%d] ",i);
for (j=0;j<no_of_resources;j++)
scanf("%d", &MAX[i][j]);
}
printf("\n");
A: a=-1;
for (i=0;i <process;i++) {
cnt=0;
b=P[i];
for (j=0;j<no_of_resources;j++) {
need[b][j] = MAX[b][j]-allocated[b][j];
if(need[b][j]<=availability[j])
cnt++;
}
if(cnt==no_of_resources) {
op[k++]=P[i];
for (j=0;j<no_of_resources;j++)
availability[j]+=allocated[b][j];
} else
P[++a]=P[i];
}
if(a!=-1) {
process=a+1;
goto A;
}
printf("\t <");
for (i=0;i<k;i++)
printf(" P[%d] ",op[i]);
printf(">");
getch();
}
Dining Philosophers problem for implementing process synchronization using C

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>

sem_t room; // counting semaphore


sem_t chopstick[5]; // binary semaphore

void * philosopher(void *);


void eat(int);

void eat(int phil)


{
printf("\nPhilosopher %d is eating",phil);
}

int main()
{
int i,a[5];
pthread_t tid[5]; // creation of threads refering to 5 philosophers

sem_init(&room,0,4); // initializations of semaphore varring from 0 to 4.

for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1); //initializations of binary semaphore .

for(i=0;i<5;i++){
a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]); // creation of philosopher
and assigning it a number.
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL); // waits until a thread gets terminated
}

void * philosopher(void * num)


{
int phil=*(int *)num;

sem_wait(&room); // semaphore function to checks if resources are available.


printf("\nPhilosopher %d has entered room",phil);
sem_wait(&chopstick[phil]); // semaphore function to checks if chopstick is available.
sem_wait(&chopstick[(phil+1)%5]);

eat(phil);
sleep(2);
printf("\nPhilosopher %d has finished eating",phil);

sem_post(&chopstick[(phil+1)%5]); // gives confirmation if semophore is released


successfully
sem_post(&chopstick[phil]);
sem_post(&room);
}

Sample program -2
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define NUM_PHILOSOPHERS 5
#define NUM_CHOPSTICKS 5

void dine(int n);


pthread_t philosopher[NUM_PHILOSOPHERS];
pthread_mutex_t chopstick[NUM_CHOPSTICKS];

int main()
{
// Define counter var i and status_message
int i, status_message;
void *msg;

// Initialise the semaphore array


for (i = 1; i <= NUM_CHOPSTICKS; i++)
{
status_message = pthread_mutex_init(&chopstick[i], NULL);
// Check if the mutex is initialised successfully
if (status_message == -1)
{
printf("\n Mutex initialization failed");
exit(1);
}
}

// Run the philosopher Threads using *dine() function


for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_create(&philosopher[i], NULL, (void *)dine, (int
*)i);
if (status_message != 0)
{
printf("\n Thread creation error \n");
exit(1);
}
}

// Wait for all philosophers threads to complete executing (finish dining)


before closing the program
for (i = 1; i <= NUM_PHILOSOPHERS; i++)
{
status_message = pthread_join(philosopher[i], &msg);
if (status_message != 0)
{
printf("\n Thread join failed \n");
exit(1);
}
}

// Destroy the chopstick Mutex array


for (i = 1; i <= NUM_CHOPSTICKS; i++)
{
status_message = pthread_mutex_destroy(&chopstick[i]);
if (status_message != 0)
{
printf("\n Mutex Destroyed \n");
exit(1);
}
}
return 0;
}
void dine(int n)
{
printf("\nPhilosopher % d is thinking ", n);

// Philosopher picks up the left chopstick (wait)


pthread_mutex_lock(&chopstick[n]);

// Philosopher picks up the right chopstick (wait)


pthread_mutex_lock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);

// After picking up both the chopstick philosopher starts eating


printf("\nPhilosopher % d is eating ", n);
sleep(3);

// Philosopher places down the left chopstick (signal)


pthread_mutex_unlock(&chopstick[n]);

// Philosopher places down the right chopstick (signal)


pthread_mutex_unlock(&chopstick[(n + 1) % NUM_CHOPSTICKS]);

// Philosopher finishes eating


printf("\nPhilosopher % d Finished eating ", n);
}

#include<stdio.h>
#include<conio.h>
main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;
int s[10], fno[10][20];

clrscr();

printf("\nEnter the memory size -- ");


scanf("%d",&ms);

printf("\nEnter the page size -- ");


scanf("%d",&ps);

nop = ms/ps;
printf("\nThe no. of pages available in memory are -- %d ",nop);

printf("\nEnter number of processes -- ");


scanf("%d",&np);
rempages = nop;
for(i=1;i<=np;i++)

printf("\nEnter no. of pages required for p[%d]-- ",i);


scanf("%d",&s[i]);

if(s[i] >rempages)
{

printf("\nMemory is Full");
break;
}
rempages = rempages - s[i];

printf("\nEnter pagetable for p[%d] --- ",i);


for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}

printf("\nEnter Logical Address to find Physical Address ");


printf("\nEnter process no. and pagenumber and offset -- ");

scanf("%d %d %d",&x,&y, &offset);

if(x>np || y>=s[i] || offset>=ps)


printf("\nInvalid Process or Page Number or offset");
else
{ pa=fno[x][y]*ps+offset;
printf("\nThe Physical Address is -- %d",pa);

}
getch();
}

Sample C program to simulate the following contiguous memory allocation techniques


a) Worst-fit b) Best-fit c) First-fit
DESCRIPTION
One of the simplest methods for memory allocation is to divide memory into several fixed-
sized partitions. Each partition may contain exactly one process. In this multiple-partition method,
when a partition is free, a process is selected from the input queue and is loaded into the free
partition. When the process terminates, the partition becomes available for another process. The
operating system keeps a table indicating which parts of memory are available and which are
occupied. Finally, when a process arrives and needs memory, a memory section large enough for this
process is provided. When it is time to load or swap a process into main memory, and if there is more
than one free block of memory of sufficient size, then the operating system must decide which free
block to allocate. Best-fit strategy chooses the block that is closest in size to the request. First-fit
chooses the first available block that is large enough. Worst-fit chooses the largest available block.

PROGRAM

a)WORST-FIT

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

b) Best-fit

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
clrscr();
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;

lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment");
for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}
c) First-fit

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - Worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{

for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

INPUT

Enter the number of blocks: 3


Enter the number of files: 2

Enter the size of the blocks:-


Block 1: 5
Block 2: 2
Block 3: 7

Enter the size of the files:-


File 1: 1
File 2: 4

OUTPUT
File No File Size Block No Block Size Fragment
1 1 3 7 6
2 4 1 5 1

Sample program for optimal page replacement algorithm


#include <stdio.h>

// This function checks if current strea item(key) exists in any of the frames or not
int search(int key, int frame_items[], int frame_occupied)
{
for (int i = 0; i < frame_occupied; i++)
if (frame_items[i] == key)
return 1;
return 0;
}

void printOuterStructure(int max_frames){


printf("Stream ");

for(int i = 0; i < max_frames; i++)


printf("Frame%d ", i+1);
}
void printCurrFrames(int item, int frame_items[], int frame_occupied, int max_frames){

// print current reference stream item


printf("\n%d \t\t", item);

// print frame occupants one by one


for(int i = 0; i < max_frames; i++){
if(i < frame_occupied)
printf("%d \t\t", frame_items[i]);
else
printf("- \t\t");
}
}
// This Function helps in finding frame that will not be used
// for the longest period of time in future in ref_str[0 ... refStrLen - 1]
int predict(int ref_str[], int frame_items[], int refStrLen, int index, int frame_occupied)
{
// For each current occupant in frame item
// we try to find the frame item that will not be referenced in
// for the longest in future in the upcoming reference string
int result = -1, farthest = index;
for (int i = 0; i < frame_occupied; i++) {
int j;
for (j = index; j < refStrLen; j++)
{
if (frame_items[i] == ref_str[j])
{
if (j > farthest) {
farthest = j;
result = i;
}
break;
}
}

// If we find a page that is never referenced in future,


// return it immediately as its the best
if (j == refStrLen)
return i;
}

// If none of the frame items appear in reference string


// in the future then we return 0th index. Otherwise we return result
return (result == -1) ? 0 : result;
}

void optimalPage(int ref_str[], int refStrLen, int frame_items[], int max_frames)


{
// initially none of the frames are occupied
int frame_occupied = 0;
printOuterStructure(max_frames);

// Here we traverse through reference string


// and check for miss and hit.
int hits = 0;
for (int i = 0; i < refStrLen; i++) {

// If found already in the frame items : HIT


if (search(ref_str[i], frame_items, frame_occupied)) {
hits++;
printCurrFrames(ref_str[i], frame_items, frame_occupied, max_frames);
continue;
}

// If not found in frame items : MISS

// If frames are empty then current reference string item in frame


if (frame_occupied < max_frames){
frame_items[frame_occupied] = ref_str[i];
frame_occupied++;
printCurrFrames(ref_str[i], frame_items, frame_occupied, max_frames);
}
// else we need to use optmial algorithm to find
// frame index where we need to do replacement for this
// incoming reference string item
else {
int pos = predict(ref_str, frame_items, refStrLen, i + 1, frame_occupied);
frame_items[pos] = ref_str[i];
printCurrFrames(ref_str[i], frame_items, frame_occupied, max_frames);
}

}
printf("\n\nHits: %d\n", hits);
printf("Misses: %d", refStrLen - hits);
}

// Driver Function
int main()
{
// int ref_str[] = {9, 0, 5, 1, 0, 3, 0, 4, 1, 3, 0, 3, 1, 3};
int ref_str[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1};
int refStrLen = sizeof(ref_str) / sizeof(ref_str[0]);
int max_frames = 3;
int frame_items[max_frames];

optimalPage(ref_str, refStrLen, frame_items, max_frames);


return 0;
}

Algorithm for FIFO Page Replacement


 Step 1. Start to traverse the pages.

 Step 2. If the memory holds fewer pages, then the capacity else goes to step 5.

 Step 3. Push pages in the queue one at a time until the queue reaches its maximum capacity
or all page requests are fulfilled.

 Step 4. If the current page is present in the memory, do nothing.

 Step 5. Else, pop the topmost page from the queue as it was inserted first.

 Step 6. Replace the topmost page with the current page from the string.

 Step 7. Increment the page faults.

 Step 8. Stop

Program

// C program for FIFO page replacement algorithm

#include<stdio.h>

int main()

int incomingStream[] = {4, 1, 2, 4, 5};

int pageFaults = 0;

int frames = 3;

int m, n, s, pages;

pages = sizeof(incomingStream)/sizeof(incomingStream[0]);

printf("Incoming \t Frame 1 \t Frame 2 \t Frame 3");

int temp[frames];

for(m = 0; m < frames; m++)

temp[m] = -1;

for(m = 0; m < pages; m++)

{
s = 0;

for(n = 0; n < frames; n++)

if(incomingStream[m] == temp[n])

s++;

pageFaults--;

pageFaults++;

if((pageFaults <= frames) && (s == 0))

temp[m] = incomingStream[m];

else if(s == 0)

temp[(pageFaults - 1) % frames] = incomingStream[m];

printf("\n");

printf("%d\t\t\t",incomingStream[m]);

for(n = 0; n < frames; n++)

if(temp[n] != -1)

printf(" %d\t\t\t", temp[n]);

else

printf(" - \t\t\t");

}
printf("\nTotal Page Faults:\t%d\n", pageFaults);

return 0;

LRU – Sample program

#include<stdio.h>

#include<limits.h>

int checkHit(int incomingPage, int queue[], int occupied){

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

if(incomingPage == queue[i])

return 1;

return 0;

void printFrame(int queue[], int occupied)

for(int i = 0; i < occupied; i++)

printf("%d\t\t\t",queue[i]);

int main()

// int incomingStream[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1};


// int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3, 6, 1, 2, 4, 3};

int incomingStream[] = {1, 2, 3, 2, 1, 5, 2, 1, 6, 2, 5, 6, 3, 1, 3};

int n = sizeof(incomingStream)/sizeof(incomingStream[0]);

int frames = 3;

int queue[n];

int distance[n];

int occupied = 0;

int pagefault = 0;

printf("Page\t Frame1 \t Frame2 \t Frame3\n");

for(int i = 0;i < n; i++)

printf("%d: \t\t",incomingStream[i]);

// what if currently in frame 7

// next item that appears also 7

// didnt write condition for HIT

if(checkHit(incomingStream[i], queue, occupied)){

printFrame(queue, occupied);

// filling when frame(s) is/are empty

else if(occupied < frames){

queue[occupied] = incomingStream[i];

pagefault++;

occupied++;

printFrame(queue, occupied);

}
else{

int max = INT_MIN;

int index;

// get LRU distance for each item in frame

for (int j = 0; j < frames; j++)

distance[j] = 0;

// traverse in reverse direction to find

// at what distance frame item occurred last

for(int k = i - 1; k >= 0; k--)

++distance[j];

if(queue[j] == incomingStream[k])

break;

// find frame item with max distance for LRU

// also notes the index of frame item in queue

// which appears furthest(max distance)

if(distance[j] > max){

max = distance[j];

index = j;

queue[index] = incomingStream[i];

printFrame(queue, occupied);

pagefault++;

}
printf("\n");

printf("Page Fault: %d",pagefault);

return 0;

}
Part-1: Where the buffer size is infinite –
In this case, the buffer from where the producer stores the item and the
consumer consumes the item size is not fixed

Program for producer consumer problem using C++

#include<bits/stdc++.h>
#include<pthread.h>
#include<semaphore.h>
#include <unistd.h>
using namespace std;

// Declaration
int r1,total_produced=0,total_consume=0;

// Semaphore declaration
sem_t notEmpty;

// Producer Section
void* produce(void *arg){
while(1){
cout<<"Producer produces item."<<endl;
cout<<"Total produced = "<<++total_produced<<
" Total consume = "<<total_consume*-1<<endl;
sem_post(¬Empty);
sleep(rand()%100*0.01);
}
}

// Consumer Section
void* consume(void *arg){
while(1){
sem_wait(¬Empty);
cout<<"Consumer consumes item."<<endl;
cout<<"Total produced = "<<total_produced<<
" Total consume = "<<(--total_consume)*-1<<endl;
sleep(rand()%100*0.01);
}
}

int main(int argv,char *argc[]){

// thread declaration
pthread_t producer,consumer;

// Declaration of attribute......
pthread_attr_t attr;

// semaphore initialization
sem_init(¬Empty,0,0);
// pthread_attr_t initialization
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);

// Creation of process
r1=pthread_create(&producer,&attr,produce,NULL);
if(r1){
cout<<"Error in creating thread"<<endl;
exit(-1);
}

r1=pthread_create(&consumer,&attr,consume,NULL);
if(r1){
cout<<"Error in creating thread"<<endl;
exit(-1);
}

// destroying the pthread_attr


pthread_attr_destroy(&attr);

// Joining the thread


r1=pthread_join(producer,NULL);
if(r1){
cout<<"Error in joining thread"<<endl;
exit(-1);
}

r1=pthread_join(consumer,NULL);
if(r1){
cout<<"Error in joining thread"<<endl;
exit(-1);
}

// Exiting thread
pthread_exit(NULL);

return 0;
}

Part-2: Where the buffer size is fixed or finite –


In this case, the buffer from where the producer stores the item and the
consumer consumes the item size is fixed.

Sample program for Part 2 in C++


#include <bits/stdc++.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
using namespace std;

// Declaration
int r1, items = 0;

// Semaphore declaration
sem_t notEmpty, notFull;

// Producer Section
void* produce(void* arg)
{
while (1) {
sem_wait(¬Full);
sleep(rand() % 100 * 0.01);
cout <<
"Producer produces item.Items Present = "
<< ++items << endl;
sem_post(¬Empty);
sleep(rand() % 100 * 0.01);
}
}

// Consumer Section
void* consume(void* arg)
{
while (1) {
sem_wait(¬Empty);
sleep(rand() % 100 * 0.01);
cout <<
"Consumer consumes item.Items Present = "
<< --items << endl;
sem_post(¬Full);
sleep(rand() % 100 * 0.01);
}
}

int main(int argv, char* argc[])


{

int N;
cout <<
"Enter the capacity of the buffer" << endl;
cin >> N;

// thread declaration
pthread_t producer, consumer;

// Declaration of attribute......
pthread_attr_t attr;

// semaphore initialization
sem_init(¬Empty, 0, 0);
sem_init(¬Full, 0, N);

// pthread_attr_t initialization
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,
PTHREAD_CREATE_JOINABLE);

// Creation of process
r1 = pthread_create(&producer, &attr,
produce, NULL);
if (r1) {
cout <<
"Error in creating thread" << endl;
exit(-1);
}
r1 = pthread_create(&consumer, &attr,
consume, NULL);
if (r1) {
cout <<
"Error in creating thread" << endl;
exit(-1);
}

// destroying the pthread_attr


pthread_attr_destroy(&attr);

// Joining the thread


r1 = pthread_join(producer, NULL);
if (r1) {
cout << "Error in joining thread" << endl;
exit(-1);
}

r1 = pthread_join(consumer, NULL);
if (r1) {
cout << "Error in joining thread" << endl;
exit(-1);
}

// Exiting thread
pthread_exit(NULL);

return 0;
}

Program for Producer and Consumer in C for Bounded Buffer( Finite Size)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define BUFFER_SIZE 5
#define MAX_ITEMS 5

int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int produced_count = 0;
int consumed_count = 0;

pthread_mutex_t mutex;
pthread_cond_t full;
pthread_cond_t empty;

void* producer(void* arg) {


int item = 1;

while (produced_count < MAX_ITEMS) {


pthread_mutex_lock(&mutex);

while (((in + 1) % BUFFER_SIZE) == out) {


pthread_cond_wait(&empty, &mutex);
}

buffer[in] = item;
printf("Produced: %d", item);
item++;
in = (in + 1) % BUFFER_SIZE;

produced_count++;

pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}

void* consumer(void* arg) {


while (consumed_count < MAX_ITEMS) {
pthread_mutex_lock(&mutex);

while (in == out) {


pthread_cond_wait(&full, &mutex);
}

int item = buffer[out];


printf("Consumed: %d", item);
out = (out + 1) % BUFFER_SIZE;

consumed_count++;

pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}

pthread_exit(NULL);
}

int main() {
pthread_t producerThread, consumerThread;

pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&full, NULL);
pthread_cond_init(&empty, NULL);

pthread_create(&producerThread, NULL, producer, NULL);


pthread_create(&consumerThread, NULL, consumer, NULL);

pthread_join(producerThread, NULL);
pthread_join(consumerThread, NULL);

pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&full);
pthread_cond_destroy(&empty);

return 0;
}
//Resource Allocation Graph using c++
#include<iostream>
using namespace std;
int main()
{
int Resources[6][6],Process[5];
int resource=0,i,j,n,row,column,count=-1;
cout<<"I have implemented a 4x3 matrix for resource allocation"<<endl;
cout<<"4 processes and 3 columns of resources"<<endl;
cout<<"Process Sequence"<<endl;
cout<<"Enter the number of processes"<<endl;
cin>>n;
cout<<"Enter Process Numbers (0-4)"<<endl;
for(i=0;i<n;i++)
{
cin>>Process[i];//Process count is entered here.Preferably 4-5 processes can be considered
}
cout<<"Enter number of rows for resource array"<<endl;
cin>>row; //Program is designed to handle 4 rows
cout<<"Enter number of columns for resource array"<<endl;
cin>>column; //Program is designed to handle 3 columns
cout<<"Enter resources"<<endl;
for(i=0;i<row;i++)
{
for(j=0;j<column;j++)
{
cin>>Resources[i][j]; //Resources are allocated in a i x j matrix
}
}
cout<<"Process Show"<<endl;
for(i=0;i<n;i++)
{
cout<<"P"<<Process[i]<<endl; //To display processes
}
cout<<"Resource Matrix Process Number"<<endl;
cout<<"A "<<" B "<<" C "<<endl;
for(i=0;i<1;i++)
{
for(j=0;j<1;j++)
{
cout<<Resources[0][0]<<" "<<Resources[0][1]<<" "<<Resources[0][2]<<" <--
"<<Process[0]<<endl;
cout<<Resources[1][0]<<" "<<Resources[1][1]<<" "<<Resources[1][2]<<" <--
"<<Process[1]<<endl;
cout<<Resources[2][0]<<" "<<Resources[2][1]<<" "<<Resources[2][2]<<" <--
"<<Process[2]<<endl;
cout<<Resources[3][0]<<" "<<Resources[3][1]<<" "<<Resources[3][2]<<" <--
"<<Process[3]<<endl;
}
}
cout<<"Check for Resource Competition/Possibility of Deadlock"<<endl;
cout<<"Please check resource matrix"<<endl;
cout<<"Enter a resource to check if collision happens"<<endl;
cin>>resource;
for(i=0;i<row;i++)
{
for(j=0;j<column;j++)
{
if(resource==Resources[i][j])
{
cout<<"Matches[row][column] "<<i<<" "<<j<<endl;
count=count+1;
}
}
}
cout<<"Counts of deadlock = "<<count<<endl;
return 0;
}

8. Example program for Implementation of resource allocation graph (RAG) using C


#include<stdio.h>
int main()
{
int np, nr, temp, temp1;
printf("enter number of resources: ");
scanf("%d", &nr);
printf("enter number of processs: ");
scanf("%d", &np);
int rag[nr+np][nr+np];
int i, j;
for(i=0;i<np+nr;i++)
{
for(j=0; j<np+nr;j++)
{
rag[i][j]=0;
}
}
for(i=0;i<np;i++)
{
printf("enter the number of resources process %d, holding", i);
scanf("%d", &temp);
for(j=0; j<temp;j++)
{
printf("enter the ressorce number process %d holding: ", j);
scanf("%d", &temp1); rag[np+temp1][i]=1;
}
printf("enter the number of resources process %d, requesting", i);
scanf("%d", &temp);
for(j=0; j<temp;j++)
{
printf("enter the ressorce number process %d requesting: ", i);
scanf("%d", &temp1);
rag[i][np+temp1]=1;
}
}
for(i=0;i<np+nr;i++)
{
for(j=0; j<np+nr;j++)
{
printf("%d ", rag[i][j]);
}
printf("\n ");
}
return 0;
}
C program for implementation of SJF
#include <stdio.h>
int main()
{
// Matrix for storing Process Id, Burst
// Time, Average Waiting Time & Average
// Turn Around Time.
int A[100][4];
int i, j, n, total = 0, index, temp;
float avg_wt, avg_tat;
printf("Enter number of process: ");
scanf("%d", &n);
printf("Enter Burst Time:\n");
// User Input Burst Time and alloting Process Id.
for (i = 0; i < n; i++) {
printf("P%d: ", i + 1);
scanf("%d", &A[i][1]);
A[i][0] = i + 1;
}
// Sorting process according to their Burst Time.
for (i = 0; i < n; i++) {
index = i;
for (j = i + 1; j < n; j++)
if (A[j][1] < A[index][1])
index = j;
temp = A[i][1];
A[i][1] = A[index][1];
A[index][1] = temp;

temp = A[i][0];
A[i][0] = A[index][0];
A[index][0] = temp;
}
A[0][2] = 0;
// Calculation of Waiting Times
for (i = 1; i < n; i++) {
A[i][2] = 0;
for (j = 0; j < i; j++)
A[i][2] += A[j][1];
total += A[i][2];
}
avg_wt = (float)total / n;
total = 0;
printf("P BT WT TAT\n");
// Calculation of Turn Around Time and printing the
// data.
for (i = 0; i < n; i++) {
A[i][3] = A[i][1] + A[i][2];
total += A[i][3];
printf("P%d %d %d %d\n", A[i][0],
A[i][1], A[i][2], A[i][3]);
}
avg_tat = (float)total / n;
printf("Average Waiting Time= %f", avg_wt);
printf("\nAverage Turnaround Time= %f", avg_tat);
}

C program for implementation of FCFS


// scheduling
#include<stdio.h>
// Function to find the waiting time for all
// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details


printf("Processes Burst time Waiting time Turn around time\n");

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf(" %d ",(i+1));
printf(" %d ", bt[i] );
printf(" %d",wt[i] );
printf(" %d\n",tat[i] );
}
float s=(float)total_wt / (float)n;
float t=(float)total_tat / (float)n;
printf("Average waiting time = %f",s);
printf("\n");
printf("Average turn around time = %f ",t);
}

// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


int burst_time[] = {10, 5, 8};

findavgTime(processes, n, burst_time);
return 0;
}

Multilevel Queue Scheduling


#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;
}

#include<stdio.h>
#include<stdlib.h>
struct process {
int process_id;
int burst_time;
int priority;
int waiting_time;
int turnaround_time;
};

void find_waiting_time(struct process[], int, int[]);


void find_turnaround_time(struct process[], int, int[], int[]);
void find_average_time(struct process[], int);
void priority_scheduling(struct process[], int);

int main()
{
int n, i;
struct process proc[10];

printf("Enter the number of processes: ");


scanf("%d", &n);

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


{
printf("\nEnter the process ID: ");
scanf("%d", &proc[i].process_id);

printf("Enter the burst time: ");


scanf("%d", &proc[i].burst_time);

printf("Enter the priority: ");


scanf("%d", &proc[i].priority);
}

priority_scheduling(proc, n);
return 0;
}

void find_waiting_time(struct process proc[], int n, int wt[])


{
int i;
wt[0] = 0;

for(i = 1; i< n; i++)


{
wt[i] = proc[i - 1].burst_time + wt[i - 1];
}
}
void find_turnaround_time(struct process proc[], int n, int wt[], int tat[])

{
int i;
for(i = 0; i< n; i++)
{
tat[i] = proc[i].burst_time + wt[i];
}
}

void find_average_time(struct process proc[], int n)


{
int wt[10], tat[10], total_wt = 0, total_tat = 0, i;

find_waiting_time(proc, n, wt);
find_turnaround_time(proc, n, wt, tat);

printf("\nProcess ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time


");

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


{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", proc[i].process_id, proc[i].burst_tim
e, proc[i].priority, wt[i], tat[i]);
}

printf("\n\nAverage Waiting Time = %f", (float)total_wtotal_wt/n);


printf("\nAverage Turnaround Time = %f\n", (float)total_tat/n);
}

void priority_scheduling(struct process proc[], int n)


{
int i, j, pos;
struct process temp;
for(i = 0; i< n; i++)
{
pos = i;
for(j = i + 1; j < n; j++)
{
if(proc[j].priority< proc[pos].priority)
pos = j;
}

temp = proc[i];
proc[i] = proc[pos];
proc[pos] = temp;
}
find_average_time(proc, n);
}

Sample program for implementing segmentation using C


#include <stdio.h>
int main()
{
int n,nm,p,x=0,y=1,t=300,of,i;
printf("Enter the memory size:\n");
scanf("%d",&nm);
printf("Enter the no.of segments:\n");
scanf("%d",&n);
int s[n];
for(i=0;i<n;i++)
{
printf("enter the segment size of %d:",i+1);
scanf("%d",&s[i]);
x+=s[i];
if(x>nm)
{
printf("memory full segment %d is not allocated",i+1);
x-=s[i];
s[i]=0;
}
}
printf("-----OPERATIONS------");
while(y==1)
{
printf("enter the no.of operations:\n");
scanf("%d",&p);
printf("enter the offset:");
scanf("%d",&of);
if(s[p-1]==0)
{
printf("segment is not allocated\n");
}
else if(of>s[p-1])
{
printf("out of range!..");
}
else
{
printf("the segment %d the physical address is ranged from %d to %d\n the address of
operation is\n",p,t,t+s[p-1],t+of);
}
printf("press 1 to continue");
scanf("%d",&y);
}
}
2. Sample program for implementing
segmentation in memory using array
#include<stdio.h>
int main()
{
int a[10][10],b[100],i,j,n,x,base,size,seg,off;
printf("Enter the segments count\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the %d size \n",i+1);
scanf("%d",&size);
a[i][0]=size;
printf("Enter the base address\n");
scanf("%d",&base);
a[i][1]=base;

for(j=0;j<size;j++)
{
x=0;
scanf("%d",&x);
// b[base]=x;
base++;
b[base]=x;
}
}
printf("Enter the segment number and offset value \n");
scanf("%d%d",&seg,&off);
if(off<a[seg][0])
{
int abs=a[seg][1]+off;
printf("the offset is less tha %d",a[seg][0]);
printf("\n %d + %d = %d\n",a[seg][1],off,abs);
printf("the element %d is at %d ",b[abs+1],abs);
}
else
{
printf("ERROr IN LOCATING");
}
}

You might also like