Operating Systems Assignment 1
Operating Systems Assignment 1
WEEK 7
Name:Shivi Mehrotra
Batch: B3
Enrollment no.: 20103064
1.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N #define RIGHT
(phnum + 1) % N
// during putfork
sem_post(&S[phnum]);
}
}
// take up chopsticks void take_fork(int
phnum)
{
sem_wait(&mutex);
sem_post(&mutex);
sleep(1);
}
// put down chopsticks void
put_fork(int phnum)
{
sem_wait(&mutex);
test(LEFT); test(RIGHT);
sem_post(&mutex);
}
void* philosopher(void* num)
{
while (1) {
take_fork(*i);
sleep(0);
put_fork(*i);
}
}
int main()
{
int i;
pthread_t thread_id[N];
0, 0);
NULL);
2.
// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
// Switch Cases
switch (n) {
case 1:
case 2:
3.
// C program for the above approach
#include <stdio.h>
#include <stdlib.h>
// Initialize a mutex to 1
int mutex = 1;
// Switch Cases
switch (n) {
case 1:
// Exit Condition
case 3: exit(0);
break;
}
}
}
4.
// C++ program to illustrate Banker's Algorithm
#include<iostream>
using namespace std;
found = true;
}
}
}
// If we could not find a next process in safe //
sequence.
if (found == false)
{
cout << "System is not in safe state";
return false;
}
}
return true;
}
// Driver code
int main()
{
int processes[] = {0, 1, 2, 3, 4};
return 0;
}
5.
// Java program to illustrate Deadlock
situation class DeadlockDemo extends
Thread { static Thread mainThread;
public void run()
{
System.out.println("Child Thread waiting for" +
" main thread completion");
try {
Semaphore Customers = 0;
Semaphore Barber = 0; Mutex
Seats = 1;
int FreeSeats = N;
Barber { while(true)
{
down(Barber);
// customer is having hair cut
} else {
/* release the lock */
up(Seats);
// customer leaves
}
}
}