Top Banner Ad

BCS401 — Unit 2: Concurrent Processes

Table of Contents (23 sections)

BCS401 · Operating system · Unit 2

Concurrent Processes

Unit Scope & Exam Weightage: This unit covers the process concept, principle of concurrency, producer/consumer problem, mutual exclusion and the critical-section problem, Dekker's and Peterson's solutions, semaphores and test-and-set, dining philosophers and sleeping barber, IPC models/schemes, and process generation (fork). AKTU repeatedly asks 2-mark numerical/counting questions and 7-mark solution/comparison questions from this unit.


Importance-Wise Roadmap (BCS401 Unit 2)

Priority Exact Syllabus Topic PYQ Evidence Marks Pattern Tag
1 Semaphores (counting, binary, usage, misuse) 2024-25, 2025-26 2m + 7m Numerical + predicted
2 Dekker's and Peterson's solutions 2023-24, 2024-25 7m × 2 Repeat comparison
3 Critical section problem & mutual exclusion 2023-24, 2024-25 7m + 7m Core theory
4 Process generation (fork), producer–consumer counts 2024-25 2m + 2m Counting traps
5 IPC models, process vs. program, concurrency definition 2023-24, 2024-25, 2025-26 2m each Quick marks
6 Dining philosophers & sleeping barber Not yet asked Predicted 7m Classical problems
7 Test-and-set Not yet asked Predicted 2–7m Hardware support

Concurrency-specific examiner guidance: In semaphore numericals, write the initial value, then every PP as −1-1 and every VV as +1+1 in a single line before giving the answer. In algorithm comparisons, always evaluate against the three requirements — mutual exclusion, progress, bounded waiting — instead of merely describing the code.


1. Process Concept and Principle of Concurrency

Process: a program in execution. It consists of the program counter, stack, heap, data section, register context and a Process Control Block (PCB). A program is a passive set of instructions on disk; a process is an active entity with state and resources.

Program Process
Passive entity (file on disk) Active entity (executing instance)
Single static copy Many instances possible from one program
Has no resources allocated Owns memory, open files, CPU context
Exists without execution Created by fork/exec, dies on exit

PYQ (2024-25, 2 marks): "What is the difference between a process and a program?" Write the two rows above; add that two users may run the same editor program as two independent processes with separate PCs and stacks.

Principle of concurrency (PYQ 2023-24, 2 marks): Two or more processes execute during the same time interval. On a single CPU their instructions are interleaved (pseudo-parallel); on a multiprocessor they may execute literally in parallel. Concurrency improves resource utilization and responsiveness but creates races, so synchronization is required.

1.1 Process Generation — fork() Counting

fork() creates a new process (child); both parent and child return from the call and continue. Each subsequent fork doubles the number of existing processes.

PYQ (2024-25, 2 marks): "A process executes the following code: fork(); fork(); fork(); How many processes are created in total, including the original?"

start          1 process
fork() #1  ->  2 processes
fork() #2  ->  4 processes
fork() #3  ->  8 processes

Answer: 8 processes in total (the original plus 7 newly created children). General rule: nn unconditionally executed forks produce 2n2^n processes; children created = 2n−12^n - 1.


2. Critical Section, Mutual Exclusion and Classical Solutions

2.1 The Critical-Section Problem

Critical section: the part of a process's code that accesses a shared resource (shared variable, file, device) which must not be concurrently accessed by another process.

Formal statement: While one process executes in its critical section, no other process may be in its critical section. A valid solution must satisfy:

Requirement Meaning Failure symptom
Mutual exclusion At most one process in the critical section Data corruption / race
Progress If no one is in CS and some processes wish to enter, only those processes decide who enters next; the choice cannot be postponed indefinitely Deadlock / unnecessary blocking
Bounded waiting After a process requests entry, there is a bound on how many times other processes may enter before it Starvation

PYQ (2024-25, 7 marks): "Define the Critical Section Problem and list the conditions that a solution must satisfy." Give the definition and the three-row table; then add a short shared-counter race illustration: two processes each execute count++ which is load; add; store, and interleaving can lose one increment.

PYQ (2023-24, 7 marks): "Explain the challenges of achieving mutual exclusion in concurrent programming?" Discuss (i) race conditions from instruction interleaving, (ii) busy waiting wasting CPU cycles, (iii) deadlock if a process never releases the resource, (iv) starvation under unfair priority, (v) cache coherence/memory ordering on multicore systems, (vi) priority inversion when a low-priority process holds a lock needed by a high-priority one.

2.2 Dekker's Algorithm (software solution, two processes)

Uses flags and a turn variable:

flag[0] = flag[1] = false;  turn = 0;
// Process P0                          // Process P1
flag[0] = true;                        flag[1] = true;
while (flag[1]) {                      while (flag[0]) {
  if (turn == 1) {                       if (turn == 0) {
    flag[0] = false;                       flag[1] = false;
    while (turn == 1) ;                    while (turn == 0) ;
    flag[0] = true;                        flag[1] = true;
  }                                      }
}                                      }
critical section;                      critical section;
turn = 1;                              turn = 0;
flag[0] = false;                       flag[1] = false;

Merits: no hardware primitive needed; satisfies all three conditions. Limitations: only two processes; busy waiting; assumes atomic reads/writes; fails on modern architectures without memory barriers because compiler/CPU reordering can break the protocol.

2.3 Peterson's Algorithm (simpler two-process solution)

flag[0] = flag[1] = false;  turn = 0;
// Pi (j = 1 - i)
flag[i] = true;
turn = j;                      //yield precedence to the other process
while (flag[j] && turn == j) ; //wait only if both want in and it is j's turn
critical section;
flag[i] = false;

Analysis: mutual exclusion holds because both cannot satisfy the while condition simultaneously (only one value of turn exists). Progress holds because the process that sets turn last enters first. Bounded waiting holds because turn alternates. Limitations: two processes only; busy waiting; relies on atomic reads/writes and sequential consistency.

PYQ (2023-24, 7 marks): "Compare and contrast Dekker's and Peterson's algorithms for mutual exclusion, considering their advantages and limitation?"

Basis Dekker Peterson
Variables Two flags + turn Two flags + turn
Waiting logic Repeatedly withdraw/re-raise flag while yielding Single compact while condition
Code complexity Longer, harder to prove Shorter, easier to understand
Mutual exclusion / progress / bounded waiting All satisfied All satisfied
Processes supported 2 2
Busy waiting Yes Yes
Modern hardware Needs memory fences Needs memory fences

PYQ (2024-25, 7 marks): "Discuss the limitations of Dekker's and Peterson's solutions when applied to modern multiprocessor architectures." Answer: both assume atomic load/store and sequentially consistent memory. Modern CPUs and compilers reorder loads/stores and use per-core caches; without volatile/fences or atomic instructions, another core may observe stale flag values, so two processes can enter CS. They also spin (burn CPU cycles) and do not scale beyond two participants. Hardware atomics (test-and-set, CAS) or OS semaphores are used instead.


3. Semaphores and Hardware Synchronization

Semaphore S: an integer variable accessed only through two atomic operations:
P(S) / wait(S): while (S <= 0) ; S--;
V(S) / signal(S): S++; A binary semaphore is restricted to 0/1 (a mutex); a counting semaphore may take any non-negative value and controls a pool of resources.

3.1 Counting Semaphore Numerical

PYQ (2025-26, 2 marks): "A counting semaphore is initialized to 10. Then 6 P (wait) and 4 V (signal) operations are performed on this semaphore. What will be the resulting value of the semaphore?"

S = 10
after 6 P operations : 10 - 6 = 4
after 4 V operations :  4 + 4 = 8
Answer: S = 8

Order is immaterial here because P and V are counts; no process blocks permanently since value never needs to go below zero in aggregate.

3.2 Predicting the P10 Trap (label: predicted from the question bank)

Predicted: Nine processes P1..P9P_1..P_9 run P(mutex); critical section; V(mutex); forever. P10P_{10} runs the same code except it uses V(mutex) in place of P(mutex). What is the largest number of processes inside the critical section?

Reasoning:

  1. mutex starts at 1. Each of P1..P9P_1..P_9 must execute a successful PP (decrement) before entering; each on exit executes VV (increment).
  2. P10P_{10} never enters the CS (it has no PP), but each of its iterations performs a VV, increasing mutex without bound.
  3. Once mutex has been raised to 9 or more, all nine PiP_i can pass their PP operations before any of them releases.
  4. P10P_{10} itself is never in the CS because it never executes the PP entry step.

Answer: 9 processes — all of P1P_1 through P9P_9 can be simultaneously inside; P10P_{10} only opens the gate.

3.3 Deadlock by Lock-Ordering (label: predicted)

Predicted: S1=S2=1S1 = S2 = 1; P1P_1: wait(S1); wait(S2); and P2P_2: wait(S2); wait(S1);. Explain deadlock.

Step P1P_1 P2P_2 S1 S2
1 wait(S1) succeeds — 0 1
2 — wait(S2) succeeds 0 0
3 wait(S2) blocks — 0 0
4 — wait(S1) blocks 0 0

Both hold one semaphore and wait for the other: circular wait → deadlock. Fix: impose a global lock order (always acquire S1 before S2), or use wait(S1,S2) as one atomic operation.

3.4 Test-and-Set (hardware primitive)

boolean test_and_set(boolean *target) {
    boolean rv = *target;
    *target = true;
    return rv;
}
// mutual exclusion with shared lock = false
do {
    while (test_and_set(&lock)) ;   // atomic: returns old value
    critical section;
    lock = false;
} while (true);

The read-and-write cannot be interrupted, so two processes cannot both see false. Drawback: still busy waits; with priorities a waiting process may starve. Bounded-waiting version uses an array waiting[i] and a rotating key.


4. Classical Concurrency Problems

4.1 Bounded Buffer / Producer–Consumer

semaphore empty = N, full = 0, mutex = 1;
producer:                       consumer:
while (true) {                  while (true) {
  produce(item);                  wait(full);
  wait(empty);                    wait(mutex);
  wait(mutex);                    item = remove();
  insert(item);                   signal(mutex);
  signal(mutex);                  signal(empty);
  signal(full);                   consume(item);
}                               }

empty counts free slots, full counts available items, mutex protects the buffer. Inverting the first two waits in either process creates a deadlock (producer holds mutex while waiting for a slot the consumer cannot free).

PYQ (2024-25, 2 marks): "In a Producer-Consumer system, the buffer size is 4. If Producer produces 6 items and Consumer consumes 3, find the number of items in the buffer at the end." Net items = produced − consumed = 6−3=36 - 3 = \mathbf{3}. Since capacity is 4, the producer cannot run all six first; it must interleave, but after all operations complete 3 items remain. (If the producer attempted six consecutive productions, it would block on the fifth, so the strict sequential interpretation is impossible — mention this to show understanding.)

4.2 Dining Philosophers

Five philosophers sit around a table; each needs two chopsticks to eat and thinks otherwise. With one chopstick between neighbours and naïve wait(left); wait(right);, all five may pick one chopstick simultaneously → deadlock.

Solutions:

  1. Allow at most four philosophers to sit (breaks circular wait).
  2. Use a waiter/mutex semaphore around both pickups.
  3. Asymmetric ordering: odd philosophers pick left first, even pick right first — one always gets both.
  4. Pick up both chopsticks atomically (wait(fork[i], fork[(i+1)%5])).
semaphore fork[5] = {1,1,1,1,1};
philosopher(i):
  while (true) {
    think();
    if (i % 2 == 0) { wait(fork[i]); wait(fork[(i+1)%5]); }
    else            { wait(fork[(i+1)%5]); wait(fork[i]); }
    eat();
    signal(fork[i]); signal(fork[(i+1)%5]);
  }

4.3 Sleeping Barber

A barber sleeps when no customer is present. A customer arriving wakes the barber; if all nn waiting chairs are occupied, the customer leaves without a haircut.

semaphore customers = 0, barber = 0, mutex = 1;
int waiting = 0;
barber:                         customer:
while (true) {                  wait(mutex);
  wait(customers);                if (waiting < n) {
  wait(mutex);                      waiting++;
  waiting--;                        signal(customers);
  signal(barber);                   signal(mutex);
  signal(mutex);                    wait(barber);   // being served
  cut_hair();                    } else {
}                                  signal(mutex);  // leaves
                                 }

customers counts waiting customers, barber signals that the barber is ready; mutex protects waiting.

4.4 Interprocess Communication (IPC)

PYQ (2025-26, 2 marks): "What is interprocess communication? How can it be implemented?" IPC is the exchange of data and synchronization signals between processes. implementations: shared memory (a common mapped region, fastest, needs explicit synchronization) and message passing (kernel send/receive, safer across machines), plus pipes, named pipes, message queues, semaphores and sockets. Direct communication names the receiver; indirect communication uses a mailbox/port.

Model Addressing Blocking behaviour Example
Direct message passing send(P2, msg) / receive(P1, msg) send/receive may block or be non-blocking POSIX msgsnd
Indirect (mailbox) send(A, msg) / receive(A, msg) mailbox may be shared by many message queue
Shared memory common virtual pages no automatic blocking shmget/mmap
Pipe / socket byte stream blocking read when empty shell `

5. Exam-Ready Solved Questions (BCS401 Unit 2)

Q1 — Critical section + semaphore synchronisation (7 marks)

A critical section is a code region accessing shared data that must run atomically with respect to other such regions. Requirements: mutual exclusion, progress, bounded waiting. A binary semaphore mutex=1 enforces it: wait(mutex) at entry sets it to 0, so any second process blocks until the first executes signal(mutex) at exit. Counting semaphores extend this to kk concurrent users of a resource pool by initialising to kk.

Q2 — Dekker vs. Peterson on modern hardware (7 marks)

Use the tables in §2.2 and §2.3. Conclude: both are correct in the idealized atomic-RMW model but are teaching algorithms, not production locks; on multicore they require memory barriers or must be replaced by hardware atomics/OS mutexes.

Q3 — Practice/Predicted (label: practice; no real PYQ claim)

  1. Practice: Three processes share a semaphore S=2. Four P and three V operations occur; find the value and say how many processes are blocked. (Answer: 2−4+3=12-4+3=1; a P blocks only when the value is 0 at that moment, so the exact blocked count depends on ordering — discuss two orders.)
  2. Practice: Modify the producer code so that a producer can never hold mutex while waiting for empty; explain why the order matters.
  3. Practice: Show how two semaphores can implement a read/write lock allowing many readers or one writer.

6. Practice Question Set

  1. Define race condition with a count++ example.
  2. State the three critical-section requirements and explain the failure mode of each.
  3. Write Peterson's algorithm for P0P_0 and prove mutual exclusion in three lines.
  4. Simulate the dining-philosophers deadlock with five numbered chopsticks.
  5. What is the difference between a binary and a counting semaphore? Give one use of each.
  6. Explain why fork(); fork(); yields four processes.
  7. Compare shared-memory and message-passing IPC in a two-column table.

7. Last-Night Survival Checklist (Unit 2 only)

  1. Three requirements first: mutual exclusion, progress, bounded waiting — write them in every synchronization answer.
  2. Semaphore arithmetic: initial value, P=−1P=-1, V=+1V=+1; for fork, use 2n2^n total processes.
  3. Code patterns to reproduce: Peterson's while condition, producer/consumer three-semaphore code, test-and-set function, sleeping-barber skeleton.
  4. Deadlock vocabulary: circular wait, hold-and-wait, lock ordering; use it in dining-philosophers and lock-ordering answers.
  5. Modern-hardware caveat: always add "needs atomic operations/memory barriers" when discussing Dekker/Peterson, since that was a 2024-25 7-mark question.

Final concurrency reminder: A 7-mark answer should show the algorithm (code or pseudocode), then evaluate it against mutual exclusion / progress / bounded waiting, then state one limitation. This three-part structure is the fastest way to full marks in Unit 2.