Multi-Threading, CPU Scheduling Algorithms, and Multi-Processor Architecture
Multi-Threading Benefits and Amdahl's Law
Single-Core vs. Multi-Core Execution:
On a single-core system without threading, processes execute sequentially, occupying the CPU one process at a time. A single-threaded program cannot execute across more than one CPU core simultaneously.
When a program is implemented with multiple threads—for example, one CPU-bound thread performing mathematical computations and another I/O-bound thread performing intermittent I/O operations—the operating system improves execution efficiency:
On a single-core system, if one thread blocks while waiting for an I/O operation, the operating system context-switches another runnable thread onto the CPU, allowing execution to continue without freezing the application.
On a multi-core system, multiple threads within a single program execute simultaneously across separate physical cores.
Core Advantages of Multi-Threading:
Responsiveness: Long-running CPU-intensive operations do not block other threads, keeping applications interactive and preventing whole-system stalls.
Scalability: Enables a single program to effectively utilize multiple CPU cores concurrently.
Resource Sharing:
In multi-process architectures, executing concurrent tasks requires creating separate processes, each with dedicated memory space, code sections, and data sections. This duplicates memory even when tasks run identical code.
Threads within a single process share the same underlying code section, data section, and operating system resources, saving significant memory space while facilitating data parallelism (running identical functionality across different data segments).
Hardware Thread Support: Modern CPU architectures feature hardware threads per core, allowing multiple execution contexts to be loaded concurrently onto core hardware resources.
Amdahl's Law:
Amdahl's Law defines the theoretical limit on performance speedup achievable when parallelizing a workload across multiple processing cores.
Mathematical Formula:
represents the proportion of the application that is strictly serial ().
represents the parallelizable proportion of the application ().
represents the total number of physical processing cores.
Quantitative Evaluation Example:
Serial portion ( serial execution).
Parallel portion ( parallelizable execution, computed via ).
Core expansion: Moving from core to cores.
Substituting parameters into Amdahl's Law shows a theoretical speedup threshold yielding approximately better real-world performance scaling.
Real-Time Scheduling Algorithms and Process Example
Fundamental CPU Scheduling Algorithms:
First-Come, First-Served (FCFS): Non-preemptive scheduling policy where jobs are executed strictly in order of arrival.
Shortest Job First (SJF) / Shortest Remaining Time First (SRTF): Priority-based policy selecting the task with the smallest upcoming CPU burst time.
Priority Scheduling: Allocates CPU time based on priority rankings assigned to ready processes.
Round Robin (RR): Time-sliced preemptive algorithm allocating equal time quanta cyclically among ready processes.
Execution Problem Analysis (3-Process Example):
Process Parameter Definitions:
Process : Arrives at time .
Process : Arrives at time .
Process : Arrives at time .
Standard Non-Preemptive FCFS Scheduling:
At , is dispatched immediately as the sole process in the system.
Because FCFS is non-preemptive, runs uninterrupted until completion, while () and () arrive and wait in the ready queue.
Once completes, the scheduler evaluates the ready queue. Under SJF rules following an initial FCFS run, (shorter burst duration) is selected before .
Hypothetical Idle CPU Strategy (Future-Knowledge Model):
Consider an alternative policy where the CPU is kept deliberately idle for the initial time unit ( to ).
At , all three processes () exist concurrently in the ready queue.
Executing the short tasks first in the sequence yields:
Average waiting time = time units.
This average waiting time represents nearly a performance improvement over standard FCFS starting at .
Average turnaround time is reduced to approximately of the standard baseline turnaround time.
Practical Execution Constraint:
Operating systems cannot predict exact future arrival times or burst durations.
Modern scheduling algorithms approximate SJF/SRTF behavior by calculating an Exponential Moving Average (EMA) of historical CPU bursts to predict subsequent burst lengths.
Multilevel Queue and Multilevel Feedback Queue (MLFQ) Scheduling
Multilevel Queue Architecture:
Production operating systems split the ready queue into multiple separate queues categorized by workload types and operational requirements.
Standard Priority Ordering (Highest to Lowest):
Real-Time Processes: Require execution completion prior to strict deadlines.
System Processes: Essential OS services and drivers.
Interactive Processes: User-facing desktop/GUI applications.
Batch Processes: Non-interactive, compute-heavy background jobs.
Static Queue Placement: In a standard multilevel queue, a process is permanently assigned to one queue throughout its lifecycle.
Multilevel Feedback Queue (MLFQ):
Allows processes to move dynamically between queues based on runtime CPU consumption patterns.
MLFQ Configuration Parameters:
Total number of priority queues.
Scheduling algorithm assigned to each queue.
Queue demotion criteria (when to move a process down).
Queue promotion criteria (when to upgrade a process).
Entry criteria (which queue a process enters upon arrival).
Starvation Mitigation:
Starvation Risk: Continuous high-priority arrivals can prevent low-priority processes from obtaining CPU cycles.
Aging Technique: Priority aging periodically increases process priorities (e.g., every ) or moves long-waiting processes upward, ensuring guaranteed execution.
Detailed Three-Queue MLFQ Operational Model:
Queue 0 (Highest Priority): Managed via Round Robin (RR) with time quantum time units.
All newly created processes enter Queue 0.
If a process finishes within time units, it terminates.
If a process consumes its full time units without finishing, it is demoted to Queue 1.
Queue 1 (Medium Priority): Managed via Round Robin (RR) with time quantum time units.
Executed only when Queue 0 contains zero ready processes.
If a process consumes its full time units without finishing, it is demoted to Queue 2.
Queue 2 (Lowest Priority): Managed via First-Come, First-Served (FCFS).
Executed only when both Queue 0 and Queue 1 are completely empty.
Periodic Flush Reset: To prevent lower-queue starvation, the OS can periodically move all tasks back up to Queue 0, granting each process at least () additional high-priority time units.
Thread Scheduling and Contention Scopes (PCS vs. SCS)
Scope of Thread Scheduling:
Modern operating system schedulers manage individual threads rather than full process blocks.
Thread execution spans User-Level Threads (ULT) and Kernel-Level Threads (KLT).
Process-Contention Scope (PCS):
Operates under Many-to-Many and Many-to-One threading models.
Competition occurs within the process among user-level threads attempting to bind to available Lightweight Processes (LWPs).
Lightweight Process (LWP): A user-space data structure representing a virtual CPU that maps user-level threads to kernel-level threads.
If system resource limits reduce kernel thread availability, PCS competition increases significantly within the process context.
System-Contention Scope (SCS):
Scheduling competition occurs across all kernel-level threads system-wide to acquire physical CPU cores.
SCS scheduling is performed directly by the kernel scheduler.
Used in One-to-One thread models and for assigning kernel threads to hardware cores in Many-to-Many systems.
Multi-Core SCS Scheduling Example:
Scenario: Process structures contain user threads mapped across total kernel-level threads.
Hardware constraint: System contains a multi-core CPU with physical cores.
Execution: The kernel scheduler uses System-Contention Scope (SCS) to select which out of the active kernel-level threads execute simultaneously on the cores.
Multiple Processor Scheduling Architecture and Queuing Strategies
Multi-Processor & Multi-Core Overhead:
Scheduling complexity increases in multi-core and multi-processor topologies.
Cache overhead: Dispathing a thread away from a core invalidates its warm L1/L2 cache lines, requiring cold cache re-fetches from main memory or L3 cache upon thread resumption.
Multi-Core Ready Queue Architectures:
Common / Shared Ready Queue:
A single unified ready queue shared across all physical cores.
Advantages: Simple design; automatic workload distribution when cores become idle.
Disadvantages: Synchronization overhead and race conditions. Multiple independent cores accessing the shared queue concurrently require lock synchronization. If Core 0 and Core 1 access the queue simultaneously without locking, both cores might dispatch the exact same process (e.g., Thread ). Legacy single-core operating systems (e.g., early Linux kernels) resolved this using monolithic kernel locking, blocking all other cores whenever one core accessed kernel data structures.
Per-Core Ready Queues:
Each individual physical CPU core maintains its own dedicated ready queue.
Advantages: Eliminates global lock contention and shared data access races.
Disadvantages: Load imbalance risks. One core's queue may contain heavy tasks (e.g., burst durations of , , units), while another core's queue finishes short tasks (e.g., burst durations of , , units) and sits completely idle.
Dynamic Load Balancing Strategies:
Push Migration: A periodic background system monitor evaluates processor workload levels across all cores. If an imbalance is identified, it actively pushes waiting tasks from overloaded core queues to idle or underloaded core queues.
Pull Migration: An idle CPU core inspects the ready queues of busy neighboring cores and pulls waiting tasks to itself for immediate execution.
Real-World Parallel (Content Distribution Networks - CDNs):
CDNs manage digital video delivery across distributed networks using pull and push strategies:
Pull Strategy: Edge servers request and pull popular media files based on localized consumer viewing demands.
Push Strategy: Centralized monitoring algorithms analyze global audience trends and push video files preemptively to edge caching locations near users to minimize access latency.
Processor Affinity, Cache Utilization, and NUMA Systems
Cache Memory Topologies:
Modern CPU cores feature per-core L1 Instruction Caches and L1 Data Caches, dedicated L2 Caches per performance core/cluster, and a shared L3 Cache.
Processor Affinity Mechanisms:
Definition: The affinity policy attempts to reassign a thread to the same CPU core it executed on previously, maximizing L1/L2 cache reuse and minimizing main memory latency.
Soft Affinity: The operating system attempts to schedule a thread on its previous core, but makes no firm guarantees; if load balancing requires migration, the thread is moved to another core.
Hard Affinity: The application explicitly binds its execution to a specific, defined subset of CPU cores.
Operating System Configuration & Security Demonstration:
System Architecture Example: physical CPU cores with hyper-threading ( hardware threads per core), presenting logical CPUs (labeled CPU 0 through CPU 15) to the OS scheduler.
Setting Processor Affinity (e.g., OS Task Manager):
Interface path: Task Manager Details -> Right-click process -> "Set Affinity".
Binding an application (e.g., Chrome) strictly to logical CPUs 0, 1, 2, and 3:
Advantage: High L1/L2 cache locality across cores 0–3, preventing cache invalidation overhead across cores 4–15.
Disadvantage: Constrains application parallel execution to a maximum of 4 concurrent threads. If Chrome attempts to execute 10 threads concurrently, performance drops due to CPU resource contention on those 4 selected cores.
Security Enforcement: Operating systems explicitly prohibit clearing processor affinity entirely (selecting 0 CPUs). Allowing zero assigned CPUs would permanently freeze execution, creating a security vulnerability where malicious software could permanently suppress security or antivirus applications by zeroing out their processor affinity masks.
Non-Uniform Memory Access (NUMA):
Architectural design in multi-socket hardware where individual physical CPU sockets connect directly to their own dedicated local RAM channels.
Accessing local socket memory is fast; accessing remote socket memory attached to another physical CPU across system interconnects introduces significant access latency.
Multi-core cache hierarchies display NUMA-like latency characteristics: fetching from local L1/L2 cache is rapid, whereas fetching missing data from another core's cache or main RAM adds substantial latency.
Administrative Details
Homework Assignment #4: Currently available for student completion.
Quiz Assignment #5: Scheduled for upcoming release.