# CPU Scheduling, Semaphores & Deadlock Banker’s Formula
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Operating Systems
Canonical URL: https://gateandnet.com/exams/gate-cs/operating-systems/cpu-scheduling-semaphores-and-deadlocks

> TAT/WT numericals, counting semaphore wait/signal invariants, and minimum/maximum resource deadlock formulas.

## Deadlock Resource Allocation Shortcut

Suppose $n$ processes each require at most $k_i$ instances of a single resource type $R$:
- **Maximum resources WITH deadlock still possible:** $\sum_{i=1}^{n} (k_i - 1)$
- **Minimum resources GUARANTEEING NO deadlock:** $\left[\sum_{i=1}^{n} (k_i - 1)\right] + 1$

*Example:* 4 processes each need max $3$ tape drives. Max drives with deadlock $= 4(3 - 1) = 8$. Minimum drives for **zero deadlock** $= 8 + 1 = \mathbf{9}$!

## `fork()` System Call Process Creation

Calling `fork()` $n$ times sequentially creates **$2^n$ total processes** ($1$ original parent + $2^n - 1$ child processes).


## Solved Practice Questions & PYQs

### [GATE CS OS NAT | NAT]
A system has $5$ processes, and each process requires a maximum of $4$ instances of resource $R$ to complete execution. What is the **minimum number of instances** of $R$ that guarantees the system will **NEVER enter deadlock**?
**Correct Answer:** 16
**Solution:** Using the deadlock-avoidance threshold formula:
$$R_{\min} = \sum_{i=1}^{5} (4 - 1) + 1 = 5 \times 3 + 1 = \mathbf{16}$$

### [GATE CS OS | MCQ]
A C program executes `fork(); fork(); fork();` sequentially without any conditional branching. Including the initial parent process, how many **child** processes are newly created?
**Correct Answer:** B
**Solution:** Executing $n$ unconditional `fork()` calls produces $2^n$ total processes and **$2^n - 1$ child processes**. For $n = 3$, total processes $= 2^3 = 8$, so newly created child processes $= 8 - 1 = \mathbf{7}$.

### [GATE CS OS | MCQ]
A counting semaphore $S$ is initialized to $10$. Subsequently, $6$ `wait(P)` operations and $4$ `signal(V)` operations are completed on $S$. What is the current value of $S$?
**Correct Answer:** A
**Solution:** Each `P / wait()` decrements $S$ by $1$, and each `V / signal()` increments $S$ by $1$: $S_{\text{final}} = 10 - 6 + 4 = \mathbf{8}$.

### [UGC NET / GATE OS | MCQ]
A system has $3$ processes, each requiring at most $4$ identical units of resource $R$. What is the **minimum** number of units of $R$ that guarantees the system is **always deadlock-free**?
**Correct Answer:** B
**Solution:** Worst-case deadlock occurs if all $P = 3$ processes hold $M_i - 1 = 3$ units simultaneously ($3 \times 3 = 9$ units). Adding just **$1$ extra unit** guarantees at least one process finishes: $R_{\min} = \sum (M_i - 1) + 1 = 3(4 - 1) + 1 = \mathbf{10}$.
