Os Assignment
Os Assignment
Branch (CSE)
Key Points:
Example:
In a multitasking OS, a user can listen to music while browsing the internet. Both tasks
are executed concurrently.
● To avoid race conditions, where two or more processes try to access and modify
the same data simultaneously.
● To maintain data consistency.
● To manage critical sections where only one process should access a resource at
a time.
Working:
● wait() or P(): Decreases the semaphore count. If count < 0, the process is
blocked.
● signal() or V(): Increases the count. If there are blocked processes, one is
unblocked.
Process 1:
wait(S); // Enter critical section
// critical section code
signal(S); // Exit critical section
Process 2:
wait(S);
// critical section
signal(S);
This ensures that only one process can enter the critical section at a time.
Problem:
It demonstrates the need for mutual exclusion, synchronization, and bounded buffer
management.
Semaphores Used:
Pseudocode (Simplified):
semaphore mutex = 1;
semaphore full = 0;
semaphore empty = N; // N is buffer size
Producer:
wait(empty);
wait(mutex);
// add item to buffer
signal(mutex);
signal(full);
Consumer:
wait(full);
wait(mutex);
// remove item from buffer
signal(mutex);
signal(empty);
Problem Setup:
Issue:
If all pick up one fork at the same time, none can pick up the second fork → deadlock.
Deadlock Conditions:
Pseudocode:
def philosopher(i):
left = forks[i]
right = forks[(i+1) % 5]
if i % 2 == 0:
left.acquire()
right.acquire()
else:
right.acquire()
left.acquire()