Sub topic 2
Interprocess Communication, Threads, and CPU Scheduling
Prerequisites
This chapter assumes you know basic C (functions, pointers, headers), the difference between user mode and kernel mode, and how fork creates a child process.
Interprocess Communication
Processes have separate address spaces, so they need the kernel to move data between them. Three common mechanisms:
- Pipe: a one-way byte channel shared through file descriptors.
- Shared memory: the kernel maps one memory region into several processes. It is fast, but the processes must synchronize their access.
- Message passing: processes exchange discrete messages through the kernel.
#include <stdio.h>
#include <unistd.h>
int main(void) {
int fd[2];
char buf[32];
pipe(fd);
if (fork() == 0) {
close(fd[0]);
write(fd[1], "hi parent", 9);
_exit(0);
}
close(fd[1]);
ssize_t n = read(fd[0], buf, sizeof buf);
printf("got %zd bytes: %.*s\n", n, (int)n, buf);
return 0;
}Threads and What They Share
A thread is a flow of execution inside a process. Threads in one process share code, global variables, the heap, and open files. Each thread has its own stack, program counter, and registers. A forked child gets its own copy of memory, so its writes do not affect the parent. A thread that writes a global variable changes it for every thread in the process.
User-Level and Kernel-Level Thread Models
| Model | Who manages threads | Blocking call stops whole process? | Uses multiple CPUs? |
|---|---|---|---|
| User-level | Thread library | Yes | No |
| Kernel-level | Kernel | No | Yes |
| Hybrid (M:N) | Both | Partly | Yes |
The CPU Scheduler, the Dispatcher, and Preemption
The scheduler picks the next ready process. The dispatcher hands over the CPU: it switches context and starts the chosen process. With preemptive scheduling, a timer interrupt can take the CPU from a running process. With non-preemptive scheduling, a process keeps the CPU until it blocks or exits. Context-switch time is pure overhead.
Scheduling Criteria
- Waiting time: time spent in the ready queue.
- Turnaround time: completion time minus arrival time.
- Response time: time from arrival until the first run.
Waiting time equals turnaround time minus burst time.
First-Come First-Served and the Convoy Effect
FCFS runs processes in arrival order without preemption. Take three processes arriving at time 0 in the order P1 (burst 24), P2 (burst 3), P3 (burst 3).
Waiting times are 0, 24, and 27, so the average is 17. If P2 and P3 arrived first, the order would be P2, P3, P1. Waiting times become 0, 3, and 6, and the average drops to 3. Short jobs stuck behind one long job is the convoy effect.
Exercise
Three processes arrive at time 0 in the order P2 (burst 3), P3 (burst 3), P1 (burst 24). Under FCFS, what is the average waiting time?
Show answer
3. Waiting times are 0, 3, and 6, so the sum is 9 and the average is 9/3 = 3.