Skip to main content

Operating Systems

Processes & Threads

Start Operating Systems here: learn what the OS keeps for every process (the PCB), how a process moves between states, what a context switch costs, and how threads share the address space of their process.

~4 hrs ~0.5–1 marks · Moderate 8 samples · 8 practice · 8 cards

GATE CSE processes and threads — program vs process, process states, PCB, queues and schedulers, context switch, fork() counting, user vs kernel threads, multithreading models and IPC, with sample questions, flashcards and drills.

Learning outcomes

  • Draw the five-state process model and name the event behind every transition
  • List PCB contents and explain what is saved and restored in a context switch
  • Count processes created by fork() sequences, including conditional forks
  • Compare user-level and kernel-level threads and the many-to-one, one-to-one and many-to-many models

Processes, PCB and process states

  • A PROGRAM is a passive entity (an executable file on disk). A PROCESS is a program in execution: code (text), data, heap, stack, program counter and registers. Two processes may run the same program but are separate processes with separate address spaces.
  • The operating system describes every process by a PROCESS CONTROL BLOCK (PCB): process id (PID), process state, program counter, CPU registers, CPU-scheduling information (priority, queue pointers), memory-management information (page-table base, limits), accounting information and I/O status (open files, devices).
  • Five-state model: NEW (being created) → READY (waiting for the CPU) → RUNNING (instructions executing) → WAITING / BLOCKED (waiting for I/O or an event) → TERMINATED. Transitions: admit (New→Ready), dispatch (Ready→Running), preemption/timeout (Running→Ready), I/O or event wait (Running→Waiting), I/O completion (Waiting→Ready), exit (Running→Terminated).
  • A blocked process never goes directly to Running: after its event completes it moves to Ready and must be dispatched again. Only one process per CPU can be in the Running state at a time; many can be Ready or Waiting.
  • Many systems add SUSPENDED states (swapped out): suspend-ready and suspend-wait. The medium-term scheduler swaps processes out and in to reduce the degree of multiprogramming.
  • Queues: job queue (all processes), ready queue (in memory, ready to run), device/wait queues (one per I/O device). The PCB is moved from queue to queue as the state changes.
  • Three schedulers: LONG-TERM (job scheduler) chooses which jobs are admitted to memory and so controls the degree of multiprogramming; SHORT-TERM (CPU scheduler) chooses the next ready process, runs very frequently and must be fast; MEDIUM-TERM swaps processes in and out.
  • A good long-term scheduler mixes I/O-bound processes (many short CPU bursts) and CPU-bound processes (few long bursts) so that both CPU and devices stay busy.
  • MEMORY LAYOUT of a process (low to high address): TEXT (program code, read-only), DATA (initialised globals) and BSS (uninitialised globals), HEAP (grows upward with malloc/new) and STACK (grows downward with activation records: locals, parameters, return addresses). Each thread of the process gets its own stack but shares the rest.
  • Counting states on ONE CPU with n processes in the system: Running is at most 1 (and can be 0 if every process is blocked or the system is idle), Ready is at most n - 1, Waiting is at most n, and each of the three can be 0. GATE asks exactly these maximum/minimum questions.
  • CPU-bound vs I/O-bound: a process is I/O-bound if it spends more time doing I/O than computing; its CPU bursts are short and frequent. Scheduling must favour I/O-bound processes so devices stay busy.
  • DEGREE OF MULTIPROGRAMMING = number of processes in main memory. Raising it increases CPU utilization (1 - p^n) only until memory is overcommitted and the system starts thrashing.
TransitionCause
New → Readylong-term scheduler admits the process
Ready → Runningdispatcher gives the CPU (scheduler choice)
Running → Readytime slice expires or higher-priority process arrives (preemption)
Running → Waitingprocess requests I/O or waits for an event
Waiting → ReadyI/O or event completes
Running → Terminatedprocess finishes or is killed

Worked example

Problem. Which of these transitions is impossible in the basic five-state model: Ready→Running, Running→Waiting, Waiting→Running, Running→Ready?

Solution. Waiting→Running is impossible. When the awaited event happens the process becomes READY and has to be chosen by the short-term scheduler before it runs. The other three are normal transitions (dispatch, I/O request, preemption).

Five-state process model: New, Ready, Running, Waiting and Terminated with labelled transitions admit, dispatch, preempt, I/O wait, I/O completion and exit.
Five-state model. Waiting never goes straight to Running; the process returns to Ready first.

Context switch, modes and system calls

  • A CONTEXT SWITCH saves the state (registers, program counter, stack pointer) of the running process in its PCB and loads the saved state of the next process from its PCB. It is pure overhead: the system does no useful user work while switching. Its time depends on hardware support (number of registers, register sets, memory-management state).
  • The DISPATCHER is the module that gives control of the CPU to the process selected by the short-term scheduler: it performs the context switch, switches to user mode and jumps to the proper location in the user program. DISPATCH LATENCY is the time it takes.
  • Switching between processes also changes the address space (page-table base register, and the TLB may need to be flushed). Switching between THREADS of the same process does not change the address space, so it is cheaper.
  • Two modes: USER mode and KERNEL (supervisor, privileged) mode. Privileged instructions run only in kernel mode: I/O instructions, setting the timer, disabling interrupts, modifying memory-management registers, halt. Reading the clock or loading a general register is not privileged.
  • A SYSTEM CALL is how a user program asks the kernel for a service; it executes a TRAP (software interrupt) that switches to kernel mode, runs the kernel routine and returns to user mode. Interrupts are asynchronous (hardware), traps/exceptions are synchronous (caused by the current instruction, such as divide by zero or a page fault).
  • A MODE switch (user ↔ kernel) is lighter than a full PROCESS context switch; a system call alone does not necessarily change the running process.
  • Process creation in UNIX: fork() creates a child that is a copy of the parent and returns 0 in the child and the child’s PID in the parent. exec() replaces the process image by a new program. wait() makes the parent wait for a child to terminate.
  • ZOMBIE: a terminated process whose PCB entry remains until the parent calls wait(). ORPHAN: a process whose parent has terminated; it is adopted by init.
  • Steps of interrupt handling: the hardware finishes the current instruction, saves PC and flags, switches to kernel mode and jumps through the interrupt vector to the ISR; the ISR saves the remaining registers, services the device, then restores state and returns (IRET). A TIMER interrupt is what lets the OS preempt a running process.
  • Interrupts are maskable (can be disabled, e.g. device interrupts) or non-maskable (NMI, hardware failure). A system call number indexes the system-call table inside the kernel; parameters are passed in registers, on the stack or through a memory block.
  • Cost of switching: if a context switch takes s time units and the Round-Robin quantum is q, the useful fraction of CPU time is q / (q + s). Example: q = 4 ms and s = 1 ms gives 80% efficiency, so about 20% of the CPU is overhead.
  • What is NOT done on a thread switch inside one process: no change of page-table base, no TLB flush, no change of open-file table. What IS done: save and load registers, program counter and stack pointer.

Formulas to remember

  • RR efficiency with switch time s and quantum q = q / (q + s)
  • CPU utilization (n processes, I/O wait fraction p) = 1 - p^n
  • n sequential unconditional fork() calls create 2^n processes in total (2^n - 1 children)

Worked example

Problem. How many processes (including the original) exist after fork(); fork(); fork(); ?

Solution. Each fork doubles the number of processes, so after three forks there are 2^3 = 8 processes: the original plus 7 children. For if (fork() == 0) { fork(); } fork(); the first fork creates C1; C1 executes the inner fork creating C2; then P, C1 and C2 each execute the last fork creating C3, C4, C5 — 6 processes in total.

Left: fields of a process control block. Right: timeline where P0 runs, the kernel saves P0 state into its PCB and loads P1 state, then P1 runs.
Context switch: state of the outgoing process is saved in its PCB and the incoming PCB is loaded. The switch itself does no useful user work.

Threads and multithreading models

  • A THREAD is a basic unit of CPU utilization: it has its own thread id, program counter, register set and stack. Threads of one process SHARE code, data (globals), heap, open files and signals. A process with several threads can do several things at once and a blocked thread need not block the others (in kernel-thread systems).
  • Benefits: responsiveness, resource sharing, economy (creating and switching threads is cheaper than processes) and scalability on multiprocessors. Because memory is shared, threads need synchronization.
  • USER-LEVEL threads are managed by a library in user space: creation and switching need no kernel call (fast) but the kernel sees one process, so one blocking system call blocks the whole process and threads cannot run in parallel on several CPUs.
  • KERNEL-LEVEL threads are managed by the OS: the kernel can schedule threads on different CPUs and one thread can block without blocking the others, but creation and switching need system calls and are slower.
  • MANY-TO-ONE: many user threads map to one kernel thread (user-level library; one blocking call blocks all; no parallelism). ONE-TO-ONE: each user thread maps to a kernel thread (Linux, Windows; full concurrency but each thread costs a kernel thread). MANY-TO-MANY: m user threads multiplex over n ≤ m kernel threads (flexible, more complex).
  • Inter-process communication (IPC) is of two kinds: SHARED MEMORY (fast after setup, needs synchronization) and MESSAGE PASSING (send/receive, easier for distributed systems, slower because of kernel involvement). Pipes, sockets and message queues are examples.
  • Thread-specific data: each thread has its own stack and registers, so local variables are private, but global and heap data are shared and need protection.
  • A TWO-LEVEL model is many-to-many plus the option to bind one user thread permanently to a kernel thread. THREAD POOLS pre-create a fixed number of worker threads so a server avoids the cost of creating a thread per request and limits the number of live threads.
  • POSIX threads (pthreads) provide pthread_create, pthread_join and pthread_exit; in Linux a thread is created by clone() sharing selected resources with its creator, so the kernel treats threads and processes almost uniformly (tasks).
  • fork() in a multithreaded process: POSIX duplicates only the CALLING thread in the child; exec() replaces the entire process, including all threads. Signals are delivered to the process (some thread handles them), while thread cancellation can be deferred or asynchronous.
  • AMDAHL’S LAW: if a fraction S of a program is inherently serial and N processors are used, speedup ≤ 1 / (S + (1 - S) / N). With S = 0.25 and N = 4 the speedup is at most 1 / (0.25 + 0.1875) ≈ 2.29; even with N → ∞ it cannot exceed 1 / S = 4.

Formulas to remember

  • Amdahl speedup ≤ 1 / (S + (1 - S) / N)
FeatureUser-level threadKernel-level thread
Managed byuser libraryoperating system
Switch costvery low, no kernel callhigher, system call needed
One blocking callblocks the whole processblocks only that thread
Multiprocessor parallelismno (one kernel entity)yes
Kernel awarenessnonefull

Worked example

Problem. A process uses the many-to-one model with 4 user threads. One thread issues a blocking read(). What happens to the other three threads?

Solution. The kernel sees only one schedulable entity, so the entire process blocks and all four threads stop until the read completes. In a one-to-one model only the calling thread would block.

Three panels showing many-to-one, one-to-one and many-to-many mappings between user threads and kernel threads.
Thread models: many-to-one (no parallelism, one block stops all), one-to-one (full concurrency) and many-to-many (n kernel threads serve m user threads).

fork() counting patterns and IPC

  • fork() duplicates the calling process: the child gets a COPY of the parent’s address space (implemented lazily by copy-on-write), so a variable changed in the child is NOT seen by the parent. Both continue from the instruction after fork(): the child sees return value 0, the parent sees the child’s PID.
  • Counting rule: the total number of processes = 1 + (number of fork() executions that succeed). Draw a tree and list, for each process, which statements it executes after the fork that created it. Each process executes the code that follows its own creation point, not the code before it.
  • Short-circuit operators matter: in fork() && fork() the second fork runs only in the process that got a non-zero value (the parent), so 3 processes result; in fork() || fork() the second fork runs only in the child (value 0), again 3 processes.
  • A loop for (i = 0; i < n; i++) fork(); doubles the process count every iteration: 2^n processes. If children leave the loop (if (fork() == 0) break;) only the original parent keeps forking, creating exactly n children, i.e. n + 1 processes.
  • exec() replaces the code, data and stack of the calling process by a new program; the PID and open files stay. fork() followed by exec() is how a shell starts a program. wait() blocks the parent until a child ends and reads its exit status (removing the zombie).
  • IPC mechanisms: PIPE (unidirectional byte stream between related processes, blocks when empty or full), NAMED PIPE / FIFO (unrelated processes), MESSAGE QUEUE, SHARED MEMORY (fastest, user code must synchronize), SOCKETS (also over a network) and SIGNALS (small asynchronous notifications).
  • Message passing can be DIRECT (send(P, m), receive(Q, m)) or INDIRECT through mailboxes/ports. It can be blocking (synchronous) or non-blocking; a rendezvous occurs when both send and receive are blocking and the buffer capacity is 0.
Code fragmentTotal processesReason
fork();2one child
fork(); fork();4second fork run by both processes
fork(); fork(); fork();82^3
if (fork()) fork();3only the parent (non-zero) forks again
if (fork() == 0) fork();3only the child forks again
if (fork() == 0) fork(); fork();6P, C1, C2 each run the last fork
fork() && fork();3second fork only in the parent
fork() || fork();3second fork only in the child
for (i = 0; i < 3; i++) fork();82^3
for (i = 0; i < 3; i++) if (fork() == 0) break;4only the parent keeps looping

Worked example

Problem. int x = 5; if (fork() == 0) { x += 10; printf("%d", x); } else { wait(NULL); printf("%d", x); } What is printed, and in which order?

Solution. The child has its own copy of x, so it prints 15. The parent waits for the child to finish and prints its unchanged x = 5. Output: 15 then 5 (the parent’s wait() forces the order). Without wait() the order would be unpredictable but the values would stay 15 and 5.

Exam tips

  • Memorise the state diagram: the only way out of Waiting is to Ready, never straight to Running.
  • For fork() counting, draw the process tree: unconditional forks double the count; conditional forks only multiply the processes that satisfy the condition.
  • Threads of one process share code, data, heap and files but NOT stack, registers or program counter.
  • User-level thread switching needs no kernel; any blocking system call blocks the whole process in many-to-one.
  • Kernel-mode-only instructions: I/O, timer set, interrupt disable, memory-management registers.
Exam pattern · 8 questions

GATE sample questions & answers

8 GATE-style MCQs for Processes & Threads with full explanations. Attempt each question before revealing the answer.

Q1 Classic GATE fork() counting

How many child processes are created by the following code? main() { fork(); fork(); fork(); }

  • A) 3
  • B) 4
  • C) 7
  • D) 8
Show answer & explanation

Answer: C

Three unconditional forks give 2^3 = 8 processes in total, i.e. 7 children plus the original process.

Q2

Which of the following process state transitions is NOT possible?

  • A) Running to Ready
  • B) Running to Waiting
  • C) Waiting to Running
  • D) Ready to Running
Show answer & explanation

Answer: C

A waiting process whose event has completed first becomes Ready and must then be dispatched; it cannot move straight to Running.

Q3

Which of the following is NOT shared by the threads of the same process?

  • A) global variables
  • B) heap memory
  • C) open file descriptors
  • D) stack
Show answer & explanation

Answer: D

Each thread has a private stack (and registers and program counter). Globals, heap and open files are shared.

Q4 GATE privileged-instruction pattern

Which one of the following instructions should be executed only in kernel mode?

  • A) read the system clock
  • B) disable all interrupts
  • C) load a general-purpose register
  • D) call a user function
Show answer & explanation

Answer: B

Disabling interrupts affects the whole system and is privileged. Reading the clock and loading a register are allowed in user mode.

Q5

How many processes exist in total after the code if (fork() == 0) { fork(); } fork(); executes (including the first process)?

  • A) 4
  • B) 5
  • C) 6
  • D) 8
Show answer & explanation

Answer: C

The first fork makes C1. C1 executes the inner fork making C2. Then P, C1 and C2 each run the last fork creating three more processes. Total 3 + 3 = 6.

Q6

In the many-to-one multithreading model, when one user thread makes a blocking system call:

  • A) only that thread is blocked
  • B) the entire process is blocked
  • C) a new kernel thread is created automatically
  • D) the other threads continue on other CPUs
Show answer & explanation

Answer: B

The kernel sees only one thread of control, so the whole process blocks and no parallelism is possible.

Q7

A terminated process whose entry still remains in the process table because its parent has not yet called wait() is called a:

  • A) orphan process
  • B) daemon process
  • C) zombie process
  • D) swapped process
Show answer & explanation

Answer: C

The child has finished but its PCB (exit status) is kept until the parent reads it using wait(): that is a zombie.

Q8

The scheduler that controls the degree of multiprogramming is the:

  • A) short-term scheduler
  • B) long-term scheduler
  • C) dispatcher
  • D) interrupt handler
Show answer & explanation

Answer: B

The long-term (job) scheduler decides how many processes are admitted into memory; the short-term scheduler only picks among ready processes.

Topic drill · 8 questions

8 practice questions — Processes & Threads

Extra page-specific practice beyond the GATE samples. Attempt all 8, then reveal answers to check your reasoning.

P1

The number of processes (including the parent) created by fork(); fork(); fork(); fork(); is:

  • A) 8
  • B) 15
  • C) 16
  • D) 32
Show answer & explanation

Answer: C) 16

Four unconditional forks: 2^4 = 16 processes in total (15 children).

P2

Which of the following is a function of the dispatcher?

  • A) choosing the next process from the ready queue
  • B) context switching and giving the CPU to the chosen process
  • C) admitting new jobs into memory
  • D) swapping processes out to disk
Show answer & explanation

Answer: B) context switching and giving the CPU to the chosen process

Choosing is the scheduler’s job; the dispatcher performs the switch, moves to user mode and jumps to the right instruction.

P3

A context switch between two threads of the same process does NOT require:

  • A) saving registers
  • B) saving the program counter
  • C) changing the page-table base register
  • D) switching stacks
Show answer & explanation

Answer: C) changing the page-table base register

Threads share one address space, so the memory map does not change; registers, program counter and stack pointer still do.

P4

The process state to which a running process moves when its time quantum expires is:

  • A) waiting
  • B) ready
  • C) terminated
  • D) new
Show answer & explanation

Answer: B) ready

Preemption on timeout puts the process back at the tail of the ready queue.

P5

The number of processes in total created by if (fork()) fork(); (counting the original) is:

  • A) 2
  • B) 3
  • C) 4
  • D) 5
Show answer & explanation

Answer: B) 3

The parent forks child C1; only the parent (non-zero return) executes the second fork creating C2. Total 3.

P6

Which one of the following is NOT an advantage of kernel-level threads over user-level threads?

  • A) true parallelism on multiprocessors
  • B) one thread blocking does not block the others
  • C) faster thread creation and switching
  • D) the kernel can schedule threads individually
Show answer & explanation

Answer: C) faster thread creation and switching

Kernel threads need system calls, so creation and switching are slower than for user-level threads.

P7

A process spends 60% of its time waiting for I/O. With 3 such processes in memory, the CPU utilization (random-wait model) is:

  • A) 40%
  • B) 78.4%
  • C) 93.6%
  • D) 21.6%
Show answer & explanation

Answer: B) 78.4%

1 - p^n = 1 - 0.6^3 = 1 - 0.216 = 0.784, i.e. 78.4%.

P8

Which IPC mechanism is generally faster once it has been set up, but needs explicit synchronization?

  • A) message passing
  • B) shared memory
  • C) sockets
  • D) signals
Show answer & explanation

Answer: B) shared memory

Shared memory avoids kernel involvement per exchange, but the processes must synchronize their access themselves.

Topic FAQs

What is the difference between a process and a thread?

A process owns an address space and resources; a thread is a unit of execution inside a process with its own stack, registers and program counter but shared code, data, heap and open files. Threads are cheaper to create and switch.

What exactly is saved during a context switch?

The program counter, CPU registers, stack pointer and memory-management information of the running process are saved into its PCB, and those of the next process are loaded from its PCB. The cache and TLB contents are not saved but may become stale.

Is a system call the same as a context switch?

No. A system call is a trap into kernel mode (a mode switch). The same process continues afterwards unless the kernel decides to schedule another one. A context switch changes which process (or thread) the CPU is executing.

How do I count processes created by fork() quickly?

Draw the tree. Each fork executed by a process adds one child. For sequential unconditional forks the total doubles every time (2^n). When a fork sits inside an if on the return value, only the child or only the parent executes it, so count carefully per branch.

Quick revision · 8 cards

8 flashcards — Processes & Threads

Hover a card to reveal the answer with a 3D flip. On touch devices, tap the card or use Show answer.

Q1 What does a PCB contain?
Q2 Name the five process states.
Q3 What do threads of a process share and not share?
Q4 Long-term vs short-term vs medium-term scheduler?
Q5 What does fork() return?
Q6 Why is a user-level thread switch cheap?
Q7 Which instructions are privileged?
Q8 Interrupt vs trap?