Overview
This session moved from observing threads to scheduling them. Students built and ran a POSIX-threads C program (threads_cpu.c) and inspected it live with ps, top -H and htop, seeing one process ID shared by seven threads (six workers + main) and per-thread CPU/memory figures. The class then ran a Python simulator (scheduler_demo.py) implementing FCFS, SJF, Priority and Round Robin on the same four-process workload, computing turnaround, waiting and response times. The session closed with testing/engineering context (functional vs performance vs security testing, auto-scaling) and a discussion of why the OS stays responsive when an application misbehaves. It sits at the hardware/software boundary: the OS schedules threads on cores, and the scheduler's policy choices are what the metrics measure.
Learning outcomes
- Write, compile and run a POSIX-threads C program with
gcc -pthread, and explain whatpthread_createandpthread_joindo and do not guarantee. - Use
ps -p,top -H -pandhtop -pto observe a process's threads, per-thread CPU%, memory%, thread IDs (LWD) and load average. - Explain why a monotonic clock (
CLOCK_MONOTONIC) is used for elapsed time and compute elapsed seconds fromtv_secand nanoseconds. - Trace the
scheduler_demo.pysimulation loop: arrival admission, ready queue, policy selection, Gantt recording, completion. - Compute turnaround, waiting and response time for FCFS, SJF, Priority and Round Robin on a given process table, and compute their averages.
- Distinguish functional, performance and security testing, and explain vertical vs horizontal (auto-)scaling.
- Explain why system processes remain responsive when an application consumes ~85% CPU.
Core concepts
POSIX threads (pthreads) and the C program
Definition: pthreads is the standard interface used to create multiple execution paths within one Linux process. Why it matters: it is the concrete mechanism by which one process gets several threads that the OS scheduler must place on cores. Connection: the observed thread counts and CPU% in ps/top/htop are the direct evidence of what pthread_create produced.
_POSIX_C_SOURCE 200809Lrequests the 2008 POSIX interfaces from the system headers;200809Lis the value used.THREAD_COUNT = 6does not include the main thread: 6 worker threads + 1 main = 7 threads total. (If changed to 8, the application creates 8 threads plus the main thread.)thread_argis atypedef'd struct holding an integerid(the worker's identifier); the typedef lets the struct be referred to asthread_arg.- The elapsed-time helper (
static double ...) usesclock_gettimewithCLOCK_MONOTONIC, taking the difference oftv_sec(whole seconds) and adding the nanosecond difference divided by1e9. - Why monotonic: the system (wall-clock) time can be adjusted by the user (e.g. the displayed 19:55), whereas the running system time used by the monotonic clock cannot be adjusted.
- Worker function: converts the
thread_argpointer to the expected argument type, reads the thread number fromid, records that thread's start time, and runs CPU-intensive work with a local counter. volatile: tells the compiler that accesses to the object are observable and should not be optimized away as if irrelevant. Here the counter is local to one worker and only keeps the CPU workload meaningful; counters are not shared between workers. Explicitly stated: volatile is not a general thread synchronization mechanism.mainas process entry point: the thread-handle array and argument array live inmain's stack frame and remain alive until the workers are joined.pthread_createsemantics: it makes the worker eligible to execute; it does not guarantee the worker executes immediately or in creation order.NULLselects default thread attributes;workeris the function the new thread executes; the argument passes a pointer to that worker's argument structure; the return code is stored and a non-zero result indicates thread creation failed.- Error branch: on failure it prints to standard error (
pthread create failedwith a timestamp) and terminates the process (return 1), i.e. it comes out of the loop. pthread_join: a second loop over the same threads waits for each worker; the final message is printed only after the workers complete, thenreturn 0indicates normal termination.- Thread ID / LWD: the identifier of an individual thread as displayed by the tools.
- Thread state: whether a thread is running, runnable, sleeping or in another state is subject to the display tool and platform.
- Headers included:
pthread.h, and standard input/int/io andtime.hheaders (exact list read loosely — [unclear]; definitive list in the PDF). - Program runs for 60 seconds to give an opportunity to observe behavior.
Linux observation: ps, top, htop
Definition: tools that display process and thread information. Why it matters: they are the empirical check on what the program actually created and how the OS scheduled it. Connection: the thread counts here match the THREAD_COUNT + 1 formula.
ps -p <pid>on the running program: the command that created the threads isthreads_cpu, process id 23924; seven threads visible — one main thread plus six sub-threads.- The process id is common for all the sub-threads, but the sub-thread process ids are totally different and unique: 24, 27, 28, 29, 30, 31, 32 (as read; leading digits [unclear]); one of these is the main thread and the rest are the six sub-threads.
top -H -p <pid>with pid 23995: shows CPU% and memory% per thread; of the CPU allocated to this thread, 33.6% / 33% / 32.9% utilized; memory used 0.1%. Thread ID = LWD, identifier of an individual thread.htop -p <pid>with pid 24057: two CPUs, 0 and 1, both at 100%; load average 3.63; 56 tasks overall, 2 running; 47 threads, 2 running; the master (parent) thread created six sub-threads; owner shown as root.- After the workers finished, threads dropped from 47 to 41 (the six created threads gone); remaining threads belong to systemd, message bus, crony (time synchronization), syslog, user root.
- Load average then 1.27, average 2.26, current 1.17, previous 1.45; uptime 5 hours; display refreshes every 3–4 seconds.
- (Exact option spelling as typed for
ps/top/htop— [unclear].) topcan be used instead ofhtop— no color, textual representation, but the same data.
Thread limits and CPU behavior
Definition: how many threads can exist and what happens when they saturate cores. Why it matters: it explains why the VM did not crash at "CPU 100%". Connection: it is the bridge from the C program to the scheduling simulator.
- No hard limit on the number of threads: the limit is resource availability (cores). The VM used in class had only two cores assigned, and it was using two cores.
- Why the VM did not crash at "CPU 100%": the CPU did not reach 100%; before it reaches 100%, the function of POSIX is basically to pause the thread (exact mechanism [unclear]; recorded as stated).
- Thread scheduling: there is a scheduling method on threads too; shown in the Python program.
Threading models
Definition: how user threads map onto kernel-schedulable entities. Why it matters: the mapping decides whether one thread's blocking call stalls the others. Connection: it is the same "kernel sees only what it can schedule" idea behind the thread observation tools.
- Many-to-One model: many user threads map onto a single kernel thread. Because the kernel sees only one schedulable entity, a blocking system call in one user thread blocks all of them.
- One-to-One model: each user thread maps to one kernel thread; this is the default on Linux/Windows, which is why a blocking call in one thread does not stall the rest.
Why the system stays responsive when an application misbehaves
Definition: the OS reserves resources for itself. Why it matters: it explains why you can still inspect and kill a runaway application. Connection: it is the same "resource efficiency / fairness" criterion used to judge schedulers.
- System processes are prioritized. The OS's own functions get an allocated CPU core, which is why the machine can still show process information and let you close a non-responding application even when the desktop/laptop is not responding.
- Example of the symptom: a browser using almost 85% of the CPU can still be killed, because system processes are prioritized.
- Dedicated vs. shared resources: system processes have dedicated resources; applications do not — applications take resources whenever they are required.
- Observation rule: if you observe that one core is not being used by the application, it may be reserved for the system.
- "System" means the operating system (OS). The OS provides the resources required for the application, so it needs resources to work — "operating system is also an application."
- Amount reserved: if speaking about CPU, a dedicated CPU — maybe one core, half core, quarter core, whatever it is — will be reserved. This is what allows you to observe application behavior and, if need be, stop / end the running application. (One core / half core / quarter core are examples of granularity, not a fixed figure [unclear].)
Testing and engineering context
Definition: three testing activities and the cloud scaling options. Why it matters: the simulator is a performance-testing tool, not functional code. Connection: benchmark metrics (average waiting, turnaround, response) are exactly the simulator's outputs.
- Functional vs performance testing: functional testing certifies the developer's effort — the code runs successfully. Performance testing confirms whether the code is effective and efficient: are threads handled/limited, what is resource utilization at peak, does the program alter behavior or hang. A program that hangs should not be pushed to production, because production is not under our control while the test environment is (we can set the traffic, e.g. 100 or 1000 requests per second, and certify that the program can support 1000 user requests per second).
- Security testing (third activity, in plain user's language): looks for loopholes for somebody to enter the environment, whether they can take control of the system or only the application, and whether unrealistic/non-productive/non-customer traffic can be injected and whether that data is recorded. Depth depends on the organization.
- Why a system call is involved: an application cannot access resources directly, so the operating system comes into the picture. When the application runs it opens resources, uses CPU, memory and storage, opens ports, and has process IDs (threads in turn create processes).
- Auto-scaling (cloud): two options — vertical scaling = increasing or decreasing the resources provided to a virtual machine; horizontal scaling = adding a virtual machine, which automatically brings its CPU to handle traffic. Example: if traffic exceeds 1000 requests per second, more resources are provided via auto-scaling.
- Default threading behavior of platforms: Java (JVM executes the code), Python (the Python platform executes it), Scala, Spark — any language providing threading/multi-threading acts on it by default; multiple threads are created to speed up the application so the response goes back to the user as soon as possible. The number of threads can be controlled in code, or left to the default setting.
- Engineering use of the simulator (testing/DevOps/operations): the testing team writes code like this (not functional code) for performance testing, with benchmark values (average waiting time, average turnaround, average response, CPU execution for process 3, CPU execution for process 1, total duration). If the outcome is less than or equivalent to the benchmark, the code is certified. Operations then monitor in production whether the code utilizes resources as expected under actual traffic; if it breaches, they inform the DevOps team, who re-run with that load in the testing environment — moving from performance testing toward load testing — and the feedback goes back to the developer.
The Python simulator scheduler_demo.py
Definition: a simulator of FCFS, SJF, Priority and Round Robin with Gantt charts and performance metrics. Why it matters: it makes scheduling policies comparable on one workload. Connection: it operationalizes the workload criteria (responsiveness, throughput, fairness, resource efficiency).
Assumptions (stated before the code) - Four processes, P1 to P4, with defined priorities; CPU burst observed. - Assumption is only one CPU, but "I have two CPUs" — two cores available. - All processes start at 0 minute/millisecond. - Context switch overhead is 8 [unclear unit] — context switching is ignored. - A lower priority number represents higher priority.
Definitions
- deque (DQ): a double-ended queue. In this program it represents the ready queue used by first-come-first-served and the routing problem; it matches the basic FIFO behavior needed for both algorithms. append and pop left allow adding processes at the end and removing the oldest process from the front.
- Process dictionary: each dictionary represents one process with its information (PID, arrival, burst, priority).
- Quantum: the round-robin time quantum, set to 2 milliseconds. The simulator uses milliseconds as its abstract unit of time — it is not measuring actual wall-clock CPU execution; it is measuring actual consumption.
- simulate(policy, quantum=quantum): each invocation accepts a scheduling policy and an optional quantum; it simulates FCFS, SJF, Priority and Round Robin. Each invocation starts a fresh simulation, so execution of one algorithm does not affect another.
- Jobs setup: enumerate(processes) provides the input position of each process; **p copies the original process fields into a new dictionary; order preserves input order for deterministic tie-breaking; remaining tracks how much CPU time is still required based on the burst; first_start is None and records the first time the process executes; completion records when the process finishes.
- Arrival queue: pending is sorted jobs values by key — it sorts processes by arrival time and by their original input order.
- Simulation state: ready = deque; next_arrival = 0; time = 0; Gantt chart = null. ready contains processes that have arrived and are eligible for CPU service — only when ready does the CPU get allocated. next_arrival identifies the next process not yet admitted to the ready queue. time is the current simulated time, initialized to zero. The Gantt stores execution intervals for later display.
- Ready queue semantics: the ready queue contains processes ready to execute, not every process that exists in the system. A process waiting for I/O, for example, would not be continuously eligible for CPU execution.
- Main loop condition: continues until all processes have completion times.
- Admission block: checks next_arrival < len(pending) and pending[next_arrival].arrival <= time, appends to ready, increments next_arrival — adds every process whose arrival time is less than or equal to the current simulated time.
- Idle handling: if no process is ready, the simulated CPU advances to the next arrival time instead of executing a non-existent process. This matters when using non-zero arrival times.
- Policy selection:
- FCFS and Round Robin: pid = ready.popleft(). For FCFS the selected process runs until CPU burst completes; for round robin the process runs for at most one quantum.
- SJF: selects the process with the shortest CPU burst among ready processes (if only one ready process, the CPU is automatically allocated to it). Tie-breaking uses burst, arrival, and order.
- Priority: same approach but selects the lowest numerical priority; tie-breaking uses priority, arrival, and order.
- SJF and Priority as implemented are non-preemptive: once selected, the process completes its remaining CPU burst before the scheduler selects another process.
- First CPU start recording: job['first_start'] = time only if not already set. It is not overwritten when the process executes again. This is necessary because response time is based on the first CPU service, not the last time the process resumes. A process can be preempted by a higher-priority process and later resume; the resume time must not be used as the start, otherwise the actual output cannot be seen.
- Execution duration: for RR, duration = minimum of quantum or job['remaining']; otherwise duration = job['remaining'].
- Gantt recording: record the interval start time, advance the simulated clock, reduce the remaining CPU requirement, and append to the Gantt chart the PID, start and duration. Example: if P1 executes from time 0 to time 2, the simulator records P1 with start 0 and duration 2. If P1 executes again later, the program adds another interval rather than combining intervals — this is how preemption and subsequent resumption in round robin are shown.
- After the interval: the simulator admits processes that arrived during that interval, then decides whether the selected process completed. If job['remaining'] == 0, set job['completion'] = time; else if policy is RR, ready.append(...) — this line appends the paused process for round-robin resumption.
- Performance metrics: turnaround = completion − arrival; waiting = turnaround − burst; response = first start − arrival. Results appended with PID, completion, turnaround, waiting, response time; the function returns the Gantt chart and the results.
- Averages: computed with the sum function — average waiting, average turnaround, average response; same pattern for turnaround and response.
- Comparison loop: runs all four policies in the same work tool, in a loop, displaying results per policy — making the comparison reproducible and avoiding manually changing the process table for every algorithm.
- Central observation: scheduling is not merely about choosing which process runs next; it is about understanding the workload and balancing responsiveness, throughput, fairness and resource efficiency. If, out of six cores, only five are utilized, that also needs to be addressed — it can happen if cores are reserved for some applications or processes (example given: your own laptop).
Workload criteria and algorithm comparison
Definition: the criteria used to judge a scheduler. Why it matters: there is no "best" algorithm in the abstract. Connection: the simulator's metrics are the evidence for each criterion.
- Criteria covered so far:
Context switching
Definition: the OS activity that saves the current process's register/program-counter state and restores the next one's. Why it matters: it is pure overhead — it does no user work — so its frequency is a cost the scheduler must control. Connection: it is why the round-robin quantum cannot be made arbitrarily small.
- What happens on a transition between processes: the scheduler picks a ready process; the context switch saves the current register/PC state and restores the next one's.
- Cost: a context switch is pure overhead — it performs no user work.
- Smaller Round Robin quantum → more context switching: a smaller quantum means more expiries per unit of work, so more scheduling events and more overhead.
- There is an optimum quantum: a smaller quantum improves responsiveness but increases context-switch overhead; below a point, throughput falls.
Algorithm properties and pitfalls
Definition: the guarantees and failure modes of each policy. Why it matters: they explain why no single policy wins on every metric. Connection: they are the reasons the simulator's averages differ across policies.
- Round Robin does not always reduce average turnaround for every process — that claim is false; a smaller quantum helps responsiveness but costs context-switch overhead.
- FCFS versus Round Robin: the blanket claim that one always beats the other is false; the outcome depends on the workload and the quantum.
- Priority scheduling and starvation: a low-priority process can wait indefinitely. Aging fixes this: waiting processes gain priority until they must run. Alternatives that do not work: making starvation permanent, or only shortening every wait proportionally — neither guarantees anything.
Formulas and maths
- Elapsed seconds from
CLOCK_MONOTONIC:(end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1e9. - Total threads in the C program:
THREAD_COUNT + 1(6 + 1 = 7). - Turnaround time = completion time − arrival time.
- Waiting time = turnaround time − CPU burst.
- Response time = first CPU start − arrival time.
- Averages: average waiting / turnaround / response =
sum(metric) / number of processes. - Round-robin execution slice:
duration = min(quantum, remaining); other policies:duration = remaining. - Quantum = 2 ms in the simulator.
Worked examples
- Thread count check:
THREAD_COUNT = 6→ 7 threads inps(1 main + 6 workers); after the workers finish,htopshows 47 → 41 threads. - Gantt interval: P1 runs from time 0 to time 2 → recorded as PID P1, start 0, duration 2; a later slice of P1 is recorded as a separate interval.
- Metric computation: for a process arriving at 0 with burst 5 completing at 8: turnaround = 8 − 0 = 8; waiting = 8 − 5 = 3; response = first start − 0.
- Quantum trade-off: halving the quantum doubles the number of expiries per unit of work, so scheduling events and context-switch overhead rise; past the optimum, throughput falls even though responsiveness improves.
Key takeaways
pthread_createmakes a thread eligible, not running;pthread_joinis what guarantees the workers finished beforemainprints and returns.- One process ID, many thread IDs (LWD): the tools show the OS's view of the threads the program created.
CLOCK_MONOTONICis used because wall-clock time can be adjusted by the user.- The many-to-one threading model blocks all user threads when one makes a blocking system call; one-to-one (the Linux/Windows default) does not.
- The OS reserves CPU for itself, which is why a runaway application at ~85% CPU can still be inspected and killed.
- Scheduling is a balance of responsiveness, throughput, fairness and resource efficiency — no policy is best in the abstract.
- A smaller round-robin quantum improves responsiveness but increases context-switch overhead; there is an optimum, and round robin does not reduce turnaround for every process.
- Aging prevents starvation in priority scheduling by raising the priority of waiting processes.
Glossary
- pthreads: POSIX standard interface for creating threads inside one process.
- LWD: the per-thread identifier shown by
top -H/htop. CLOCK_MONOTONIC: a clock that cannot be adjusted by the user, used for elapsed time.- Quantum: the maximum time slice a round-robin process runs before being preempted (2 ms here).
- Ready queue: the set of arrived processes eligible for CPU service.
- Turnaround / waiting / response time: completion − arrival; turnaround − burst; first start − arrival.
- Context switch: saving the current register/PC state and restoring the next process's; pure overhead.
- Aging: gradually raising the priority of waiting processes so they eventually run.
- Many-to-One model: many user threads on one kernel thread; a blocking call stalls them all.
- One-to-One model: one kernel thread per user thread; the default on Linux/Windows.
- Vertical scaling: changing the resources of an existing VM.
- Horizontal scaling: adding a VM, which brings its own CPU to handle traffic.