session: "5102-foundations-of-comp-sys/2026-10-17 0000 FCS 17 Oct"
title: "FCS 17 Oct"
date: "2026-10-17 00:00"
duration: "1h 49m"
language: "en"
model: "deepseek-ai/DeepSeek-V4.1-Flash-1017"
parts: 3
transcript_chars: 59759
generated: "2026-11-23T15:58:13+05:30"
FCS 17 Oct
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 what pthread_create and pthread_join do and do not guarantee. - Use
ps -p, top -H -p and htop -p to 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 from tv_sec and nanoseconds. - Trace the
scheduler_demo.py simulation 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 200809L requests the 2008 POSIX interfaces from the system headers; 200809L is the value used.THREAD_COUNT = 6 does 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_arg is a typedef'd struct holding an integer id (the worker's identifier); the typedef lets the struct be referred to as thread_arg.- The elapsed-time helper (
static double ...) uses clock_gettime with CLOCK_MONOTONIC, taking the difference of tv_sec (whole seconds) and adding the nanosecond difference divided by 1e9. - 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_arg pointer to the expected argument type, reads the thread number from id, 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.main as process entry point: the thread-handle array and argument array live in main's stack frame and remain alive until the workers are joined.pthread_create semantics: it makes the worker eligible to execute; it does not guarantee the worker executes immediately or in creation order. NULL selects default thread attributes; worker is 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 failed with 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, then return 0 indicates 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 and time.h headers (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 is threads_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].) top can be used instead of htop — 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.
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.