Repository navigation
Expand file tree
/
Copy pathreport.typ
More file actions
1884 lines (1481 loc) · 60.4 KB
/
Copy pathreport.typ
File metadata and controls
1884 lines (1481 loc) · 60.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Document Configuration
#set document(
title: "CPU Scheduling Algorithms Simulation Using Data Structures",
author: "Odai Masnoor Gubran",
)
#set page(
paper: "a4",
margin: (x: 2cm, y: 2.5cm),
numbering: "1",
header: align(right)[
_CPU Scheduling Algorithms Simulation_
],
)
#set text(size: 11pt, font: "New Computer Modern")
#set heading(numbering: "1.1")
#set par(justify: true)
// Title Page
#align(center)[
#v(2cm)
#text(size: 14pt, weight: "bold")[Ar-Rasheed Smart University]
#text(size: 12pt)[College of Engineering and Information Technology]
#v(1cm)
#text(size: 24pt, weight: "bold")[
CPU Scheduling Algorithms Simulation Using Data Structures
]
#v(1cm)
#text(size: 14pt)[Data Structures and Algorithms Project]
#v(2cm)
#text(size: 12pt)[
*Theory Instructor:* Dr. Belal Murshed
*Lab Instructor:* T. Mohammed Al-Sayani
*Student Name:* Odai Masnoor Gubran
*Student ID:* 202410100532
#text(size: 10pt, fill: blue)[#link("https://github.com/odai-dev/CPU-Scheduling-Algorithms-Simulation-Using-Data-Structures")]
]
#v(2cm)
#text(size: 12pt)[February 2026]
]
#pagebreak()
// Executive Summary
#align(center)[
#text(size: 16pt, weight: "bold")[Executive Summary]
]
#v(1cm)
This project presents a comprehensive implementation and comparative analysis of classical CPU scheduling algorithms using custom-built data structures in C++. The simulator implements six algorithm variants: First Come First Serve (FCFS), Shortest Job First (SJF) in both non-preemptive and preemptive modes, Priority Scheduling in both modes, and Round Robin (RR).
All data structures—including Queue, Priority Queue (Binary Heap), Linked List, and Dynamic Array—were implemented from scratch without relying on standard library scheduling containers. The project demonstrates practical applications of these structures in operating system simulations.
Performance analysis reveals that Shortest Remaining Time First (SRTF) achieves the optimal average waiting time of 2.6 time units, while Round Robin provides superior fairness and response time for interactive systems. A graphical user interface built with Dear ImGui offers interactive visualization of process scheduling through animated Gantt charts.
*Key Technologies:* C++17, Custom Data Structures, Dear ImGui, GLFW, OpenGL, Typst
*Key Achievements:*
- Complete implementation of 6 scheduling algorithm variants
- Custom data structures with O(1) to O(log n) operations
- Comprehensive performance comparison and analysis
- Interactive GUI with real-time Gantt chart visualization
#pagebreak()
// Table of Contents
#outline(
title: "Table of Contents",
indent: auto,
depth: 3,
)
#pagebreak()
= Introduction
== Project Overview
CPU scheduling is a fundamental component of operating systems that determines the order in which processes access the CPU. This project implements a complete scheduling simulator that models real-world OS behavior, allowing for direct comparison of different scheduling policies under identical workloads.
The simulator handles diverse process characteristics including arrival times, burst times, and priorities, while accurately calculating key performance metrics such as waiting time, turnaround time, and completion time for each process.
== Project Scope
This project encompasses:
*Core Implementation:*
- Six CPU scheduling algorithm variants
- Four custom data structures built from scratch
- Comprehensive metric calculation and display
- Timeline generation for Gantt chart visualization
*Advanced Features:*
- Graphical User Interface for interactive scheduling
- Real-time animated Gantt charts
- Algorithm performance comparison tools
- Support for custom process input and predefined test cases
*Educational Value:*
- Clear demonstration of algorithm trade-offs
- Visual representation of scheduling behavior
- Practical application of data structure concepts
- Performance analysis methodology
== Aims and Objectives
The primary aims of this project are:
1. *Educational Implementation* - Design and implement a comprehensive CPU scheduling simulator that models real operating-system scheduling behaviour using C++.
2. *Algorithm Coverage* - Implement and compare multiple classical CPU scheduling algorithms:
- First Come First Serve (FCFS)
- Shortest Job First (SJF) - Non-Preemptive
- Shortest Remaining Time First (SRTF) - Preemptive SJF
- Priority Scheduling - Non-Preemptive
- Priority Scheduling - Preemptive
- Round Robin (RR)
3. *Performance Analysis* - Quantitatively analyze scheduling performance using key metrics:
- Average Waiting Time
- Average Turnaround Time
- Completion Time for each process
- Context switch overhead analysis
4. *Educational Tool* - Provide a tool that helps students understand scheduling trade-offs, starvation, fairness, preemption, and efficiency through visualization and comparison.
5. *Data Structure Application* - Demonstrate practical use of data structures (Queue, Priority Queue, Linked List, Dynamic Array) in operating-system simulations.
6. *Fair Comparison* - Enable algorithm comparison under identical workloads, ensuring fair and consistent evaluation.
== Technologies and Tools
*Programming Language:*
- C++17 with standard library support
- Object-oriented design with separate header and implementation files
*Custom Data Structures:*
- All scheduling structures implemented from scratch
- No use of STL containers for core scheduling logic
*GUI Framework:*
- Dear ImGui for immediate-mode GUI
- GLFW for window management
- OpenGL for graphics rendering
*Documentation:*
- Typst typesetting system for professional report generation
*Build Tools:*
- g++ compiler with C++17 standard
- Manual compilation and linking
#pagebreak()
= Methodology
== System Architecture
The project follows a modular architecture with clear separation of concerns:
```
┌─────────────────────────────────────────────────────┐
│ User Interface │
│ (CLI / GUI with ImGui) │
└────────────────────┬────────────────────────────────┘
│
┌───────────┴───────────┐
│ │
┌────────▼────────┐ ┌────────▼────────┐
│ Scheduler.h/cpp│ │ Process.h/cpp │
│ (Algorithms) │ │ (Process Data) │
└────────┬────────┘ └─────────────────┘
│
│
┌────────▼──────────────────────────────────────┐
│ DataStructures.h/cpp │
│ ┌──────────┐ ┌──────────┐ ┌────────────┐ │
│ │ Queue │ │Priority │ │ List │ │
│ │ (FIFO) │ │ Queue │ │ (Sorted) │ │
│ └──────────┘ └──────────┘ └────────────┘ │
└───────────────────────────────────────────────┘
```
== File Organization
#table(
columns: (auto, auto),
inset: 10pt,
[*File*], [*Purpose*],
[Process.h/cpp], [Process structure definition and implementation],
[DataStructures.h/cpp], [Custom data structure implementations],
[Scheduler.h/cpp], [All scheduling algorithms and helper functions],
[main.cpp], [Command-line interface entry point],
[gui/gui_main.cpp], [Graphical user interface implementation],
[report.typ], [Project documentation],
)
== Design Decisions
*Why Custom Data Structures?*
The project requirements explicitly prohibited use of built-in scheduling libraries. All structures were implemented from scratch to demonstrate understanding of:
- Linked list operations and memory management
- Binary heap properties and maintenance
- Queue operations and FIFO ordering
- Dynamic array resizing strategies
*Algorithm Selection Rationale:*
The six selected algorithms represent the fundamental spectrum of scheduling approaches:
- *FCFS*: Simplest algorithm, baseline for comparison
- *SJF/SRTF*: Optimal for minimizing waiting time
- *Priority*: Common in real-time systems
- *Round Robin*: Standard for time-sharing systems
*Performance Metric Choices:*
- Waiting Time: Measures queue delay
- Turnaround Time: Measures total completion time
- Both averaged across all processes for fair comparison
#pagebreak()
= Data Structures
#figure(
image("images/process_state_diagram_1770238516225.jpg", width: 80%),
caption: [Process lifecycle and state transitions in CPU scheduling]
)
This section details the custom data structures implemented for the scheduling algorithms. *No built-in scheduling libraries were used* — all structures are implemented from scratch to demonstrate understanding of fundamental data structure concepts.
== Process Structure
=== Purpose
The `Process` structure models a process with all attributes required for CPU scheduling algorithms, supporting both preemptive and non-preemptive scheduling modes.
=== Attributes
#table(
columns: (auto, auto, auto),
inset: 8pt,
align: (left, left, left),
[*Attribute*], [*Type*], [*Description*],
[`id`], [`int`], [Unique identifier for the process],
[`arrivalTime`], [`int`], [Time at which the process arrives in the ready queue],
[`burstTime`], [`int`], [Total CPU time required by the process],
[`priority`], [`int`], [Priority level (lower number = higher priority)],
[`remainingTime`], [`int`], [Tracks remaining CPU time (for preemptive scheduling)],
[`waitingTime`], [`int`], [Total time spent waiting in ready queue],
[`turnaroundTime`], [`int`], [Total time from arrival to completion],
[`completionTime`], [`int`], [Time at which the process finishes execution],
)
=== Implementation
```cpp
class Process {
public:
int id;
int arrivalTime;
int burstTime;
int priority;
// Managed by the Scheduler
int remainingTime;
int waitingTime;
int turnaroundTime;
int completionTime;
Process();
Process(int id, int arrivalTime, int burstTime, int priority = 0);
};
```
=== Key Formulas
*Waiting Time:* `WT = Completion Time - Arrival Time - Burst Time`
*Turnaround Time:* `TAT = Completion Time - Arrival Time`
*Alternative:* `TAT = WT + Burst Time`
#pagebreak()
== Node Structure
=== Purpose
A generic node for linked structures that holds process data and maintains chain connectivity.
=== Implementation
```cpp
class Node {
public:
Process data;
Node* next;
Node(Process p) : data(p), next(nullptr) {
if (data.id < 0) {
throw invalid_argument("invalid id");
}
}
};
```
=== Key Points
- Contains a `Process` object and a `next` pointer
- Used by `ProcessQueue` and `ProcessList` classes
- Includes validation to prevent invalid process IDs
- Foundation for linked list-based structures
== ProcessQueue Class (FIFO Queue)
=== Purpose
Implements a *First-In-First-Out (FIFO)* queue structure, essential for:
- *FCFS Algorithm*: Processes are served in arrival order
- *Round Robin Algorithm*: Processes cycle through the ready queue
=== Architecture
```
Queue Structure:
front rear
│ │
▼ ▼
┌────┐ ┌────┐ ┌────┐ ┌────┐
│ P1 │───▶│ P2 │───▶│ P3 │───▶│ P4 │─┐
└────┘ └────┘ └────┘ └────┘ │
▼
nullptr
```
=== Components
*Private Members:*
- `Node* front`: Pointer to the first node in the queue
- `Node* rear`: Pointer to the last node in the queue
*Public Methods:*
#table(
columns: (auto, auto, auto),
inset: 8pt,
[*Method*], [*Time Complexity*], [*Description*],
[`enqueue(Process)`], [O(1)], [Adds process to rear of queue],
[`dequeue()`], [O(1)], [Removes and returns front process],
[`getFront()`], [O(1)], [Returns front process without removing],
[`getRear()`], [O(1)], [Returns rear process without removing],
[`isEmpty()`], [O(1)], [Returns true if queue is empty],
[`print()`], [O(n)], [Displays all processes in queue],
)
=== Implementation Details
*enqueue() Operation:*
```cpp
void ProcessQueue::enqueue(Process value) {
Node* newNode = new Node(value);
if(isEmpty()) {
rear = front = newNode; // First element
return;
} else {
rear->next = newNode; // Link to end
rear = newNode; // Update rear
}
}
```
*dequeue() Operation:*
```cpp
Process ProcessQueue::dequeue() {
if(isEmpty()) {
return {-1, 0, 0, 0}; // Invalid process
}
Node* temp = front;
Process p = front->data;
if(front == rear) {
front = rear = nullptr; // Last element
} else {
front = front->next; // Move front forward
}
delete(temp);
return p;
}
```
=== Use Cases in Project
- FCFS ready queue management
- Round Robin process rotation
- Timeline data storage
#pagebreak()
== ProcessList Class (Sorted Linked List)
=== Purpose
Implements a singly-linked list with two insertion modes:
1. *Sorted Insert* (`addProcess`): Maintains arrival time order
2. *Append* (`push_back`): Adds to the end (for timeline/Gantt chart data)
=== Components
*Private Members:*
- `Node* head`: Pointer to the first node in the list
- `int count`: Number of processes in the list
*Public Methods:*
#table(
columns: (auto, auto, auto),
inset: 8pt,
[*Method*], [*Time Complexity*], [*Description*],
[`addProcess(Process)`], [O(n)], [Inserts sorted by arrival time],
[`push_back(Process)`], [O(n)], [Appends to end of list],
[`clear()`], [O(n)], [Removes all processes],
[`getHead()`], [O(1)], [Returns pointer to first node],
[`getSize()`], [O(1)], [Returns number of processes],
)
=== Sorted Insertion Algorithm
```cpp
void ProcessList::addProcess(Process p) {
Node* newNode = new Node(p);
// Insert at head if empty or p arrives earliest
if (head == nullptr || head->data.arrivalTime > p.arrivalTime) {
newNode->next = head;
head = newNode;
} else {
// Find insertion point
Node* current = head;
while (current->next != nullptr &&
current->next->data.arrivalTime <= p.arrivalTime) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
count++;
}
```
=== Use Cases in Project
- *Master Process List*: Stores all input processes sorted by arrival time
- *Execution Timeline*: Records execution slices for Gantt chart visualization
- *Completed Processes*: Stores processes after finishing execution
#pagebreak()
== DynamicArray Class
=== Purpose
A resizable array providing the foundation for the Priority Queue implementation. Automatically grows when capacity is reached using a doubling strategy.
=== Components
*Private Members:*
- `Process* data`: Pointer to the underlying array
- `int size`: Current number of elements
- `int capacity`: Maximum current capacity
- `resize()`: Doubles capacity when full
*Public Methods:*
#table(
columns: (auto, auto, auto),
inset: 8pt,
[*Method*], [*Time Complexity*], [*Description*],
[`push_back(Process)`], [O(1) amortized], [Adds element to end],
[`operator[](int)`], [O(1)], [Array-style access],
[`getSize()`], [O(1)], [Returns current size],
[`removeLast()`], [O(1)], [Removes last element],
)
=== Key Implementation
*Automatic Resizing:*
```cpp
void DynamicArray::resize() {
capacity *= 2; // Double capacity
Process* newData = new Process[capacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
delete[] data;
data = newData;
}
```
*Copy Constructor (Rule of Three):*
```cpp
DynamicArray::DynamicArray(const DynamicArray& other) {
capacity = other.capacity;
size = other.size;
data = new Process[capacity];
for (int i = 0; i < size; i++) {
data[i] = other.data[i];
}
}
```
=== Amortized Analysis
When capacity is reached, resizing takes O(n) time. However, this happens infrequently:
- Starting capacity: 4
- Resizes occur at: 4, 8, 16, 32, 64, ...
- Total insertions for n elements: n + n/2 + n/4 + ... ≈ 2n
- Amortized cost per insertion: O(1)
#pagebreak()
== PriorityQueue Class (Binary Heap)
#figure(
image("images/heap_visualization_1770238497543.jpg", width: 90%),
caption: [Binary min-heap structure for Priority Queue implementation showing parent-child relationships and array representation]
)
=== Purpose
The Priority Queue is implemented as a *Binary Heap* stored in a Dynamic Array. It supports both min-heap and max-heap modes for different scheduling algorithms:
- *Min-Heap Mode*: For SJF/SRTF — prioritizes smaller remaining time
- *Max-Heap Mode (by priority value)*: For Priority Scheduling — prioritizes lower priority numbers
=== Components
*Private Members:*
- `DynamicArray heap`: Underlying storage
- `bool isMinHeap`: Mode selector
- Helper functions:
- `parent(i) = (i-1)/2`
- `leftChild(i) = 2*i+1`
- `rightChild(i) = 2*i+2`
- `heapifyUp()`, `heapifyDown()`: Maintain heap property
- `hasHigherPriority()`: Comparison based on mode
- `swap()`: Exchange elements
*Public Methods:*
#table(
columns: (auto, auto, auto),
inset: 8pt,
[*Method*], [*Time Complexity*], [*Description*],
[`enqueue(Process)`], [O(log n)], [Adds and heapifies up],
[`dequeue()`], [O(log n)], [Removes root and heapifies down],
[`peek()`], [O(1)], [Returns root without removing],
[`isEmpty()`], [O(1)], [Checks if empty],
[`getSize()`], [O(1)], [Returns number of elements],
)
=== Priority Comparison Logic
```cpp
bool PriorityQueue::hasHigherPriority(Process p1, Process p2) {
if (isMinHeap) {
// SJF: Compare by remaining time
if (p1.remainingTime == p2.remainingTime) {
return p1.arrivalTime < p2.arrivalTime; // Tiebreaker
}
return p1.remainingTime < p2.remainingTime;
} else {
// Priority Scheduling: Compare by priority value
if (p1.priority == p2.priority) {
return p1.arrivalTime < p2.arrivalTime; // Tiebreaker
}
return p1.priority < p2.priority; // Lower number = higher priority
}
}
```
=== Heap Operations
*heapifyUp() - After Insertion:*
```cpp
void PriorityQueue::heapifyUp(int idx) {
if(idx == 0) return; // Root reached
int parentIdx = parent(idx);
if(hasHigherPriority(heap[idx], heap[parentIdx])) {
swap(idx, parentIdx);
heapifyUp(parentIdx); // Recursive
}
}
```
*heapifyDown() - After Deletion:*
```cpp
void PriorityQueue::heapifyDown(int idx) {
int left = leftChild(idx);
int right = rightChild(idx);
int highest = idx;
if (left < heap.getSize() &&
hasHigherPriority(heap[left], heap[highest])) {
highest = left;
}
if (right < heap.getSize() &&
hasHigherPriority(heap[right], heap[highest])) {
highest = right;
}
if(highest != idx) {
swap(idx, highest);
heapifyDown(highest); // Recursive
}
}
```
=== Use Cases in Project
- SJF/SRTF: Min-heap by remaining time
- Priority Scheduling: Heap by priority value
- Efficient O(log n) insertion and removal
#pagebreak()
= Scheduling Algorithms
This section provides comprehensive documentation of all six scheduling algorithm variants implemented in the project, including detailed explanations, pseudocode, implementation details, and visual representations.
== First Come First Serve (FCFS)
=== Algorithm Overview
FCFS is the simplest scheduling algorithm where processes are executed in the order they arrive in the ready queue. It is *non-preemptive* — once a process starts execution, it runs to completion without interruption.
=== Characteristics
#table(
columns: (auto, auto),
inset: 8pt,
[*Property*], [*Value*],
[Type], [Non-Preemptive],
[Starvation], [No — all processes eventually execute],
[Convoy Effect], [Yes — short processes wait for long ones],
[Overhead], [Minimal — no context switching during execution],
[Fairness], [Fair in order of arrival],
[Implementation Complexity], [Very Simple],
)
=== Algorithm Logic
1. Maintain a FIFO queue of ready processes
2. As processes arrive, add them to the queue
3. Execute process at front of queue to completion
4. Handle CPU idle time when no processes are available
5. Calculate metrics after completion
=== Implementation
```cpp
ProcessList Scheduler::runFCFS(ProcessList &masterList) {
ProcessQueue readyQueue;
int currentTime = 0;
int completed = 0;
Node* it = masterList.getHead();
int total = masterList.getSize();
ProcessList completedProcesses;
timeline.clear();
while(completed < total) {
// Add arrived processes to ready queue
while(it != nullptr && it->data.arrivalTime <= currentTime) {
readyQueue.enqueue(it->data);
it = it->next;
}
if(!readyQueue.isEmpty()) {
Process p = readyQueue.dequeue();
// Log for Gantt Chart
Process slice = p;
slice.arrivalTime = currentTime; // Start Time
slice.burstTime = p.burstTime; // Duration
timeline.push_back(slice);
p.waitingTime = currentTime - p.arrivalTime;
currentTime += p.burstTime;
p.completionTime = currentTime;
p.turnaroundTime = p.waitingTime + p.burstTime;
completedProcesses.addProcess(p);
completed++;
} else {
// Handle idle CPU - jump to next arrival
if (it != nullptr) {
currentTime = it->data.arrivalTime;
}
}
}
return completedProcesses;
}
```
=== Execution Example
#figure(
image("images/gantt_fcfs_1770238432778.jpg", width: 100%),
caption: [FCFS Gantt chart showing sequential execution in arrival order with CPU idle time]
)
#pagebreak()
== Shortest Job First (SJF)
=== Algorithm Overview
SJF selects the process with the *smallest burst time* (or remaining time in preemptive mode). This algorithm provably minimizes average waiting time but requires knowing burst times in advance.
=== Variants
*Non-Preemptive SJF:* Once started, process runs to completion
*Preemptive SJF (SRTF):* Process can be interrupted if a shorter job arrives
=== Characteristics
#table(
columns: (auto, auto, auto),
inset: 8pt,
[*Property*], [*Non-Preemptive*], [*Preemptive (SRTF)*],
[Optimal AWT], [Yes (among non-preemptive)], [Yes (overall optimal)],
[Starvation], [Possible for long jobs], [Possible for long jobs],
[Context Switches], [Low], [High (potentially every time unit)],
[Complexity], [Moderate], [High],
[Real-world Applicability], [Batch systems], [Modern OS with estimation],
)
=== Implementation Approach
1. Use a min-heap priority queue ordered by remaining time
2. When a process arrives, add it to the priority queue
3. Always execute the process with smallest remaining time
4. For preemptive: re-evaluate after each time unit
5. For non-preemptive: execute to completion
=== Implementation
```cpp
ProcessList Scheduler::runSJF(ProcessList &masterList, bool preemptive) {
PriorityQueue pq(true); // Min-heap for shortest job
int currentTime = 0;
int completed = 0;
Node* it = masterList.getHead();
int total = masterList.getSize();
ProcessList completedProcesses;
timeline.clear();
while (completed < total) {
// Add arrived processes to priority queue
while(it != nullptr && it->data.arrivalTime <= currentTime) {
pq.enqueue(it->data);
it = it->next;
}
if(!pq.isEmpty()) {
if(preemptive) {
// SRTF: Execute 1 time unit
Process p = pq.dequeue();
// Log 1-unit slice for Gantt Chart
Process slice = p;
slice.arrivalTime = currentTime;
slice.burstTime = 1;
timeline.push_back(slice);
p.remainingTime--;
currentTime++;
if(p.remainingTime > 0) pq.enqueue(p); // Re-queue
if(p.remainingTime == 0) {
p.completionTime = currentTime;
p.waitingTime = p.completionTime - p.arrivalTime - p.burstTime;
p.turnaroundTime = p.waitingTime + p.burstTime;
completed++;
completedProcesses.addProcess(p);
}
} else {
// Non-preemptive: run full burst
Process p = pq.dequeue();
// Log full slice
Process slice = p;
slice.arrivalTime = currentTime;
slice.burstTime = p.burstTime;
timeline.push_back(slice);
p.waitingTime = currentTime - p.arrivalTime;
currentTime += p.burstTime;
p.completionTime = currentTime;
p.turnaroundTime = p.waitingTime + p.burstTime;
completedProcesses.addProcess(p);
completed++;
}
} else {
if(it != nullptr) currentTime = it->data.arrivalTime;
}
}
return completedProcesses;
}
```
=== Execution Example
#figure(
image("images/gantt_sjf_preemptive_1770238478914.jpg", width: 100%),
caption: [SRTF (Preemptive SJF) showing preemption points where shorter jobs interrupt longer jobs]
)
=== Why SRTF is Optimal
SRTF minimizes average waiting time because it always executes the process closest to completion. Mathematical proof shows that any deviation from this policy increases total waiting time.
*Proof Sketch:* If we swap execution order of two processes where the first has longer remaining time, the shorter process waits longer unnecessarily, increasing average waiting time.
#pagebreak()
== Priority Scheduling
=== Algorithm Overview
Priority Scheduling assigns each process a priority value. The CPU is allocated to the process with the *highest priority* (lowest priority number in this implementation).
=== Characteristics
#table(
columns: (auto, auto),
inset: 8pt,
[*Property*], [*Value*],
[Priority Convention], [Lower number = Higher priority],
[Starvation], [Yes — low priority processes may never execute],
[Solution to Starvation], [Aging — gradually increase priority over time],
[Use Case], [Real-time systems, OS kernel tasks],
[Preemption Support], [Both preemptive and non-preemptive modes],
)
=== Implementation
```cpp
ProcessList Scheduler::runPriority(ProcessList &masterList, bool preemptive) {
PriorityQueue pq(false); // Priority-based ordering
int currentTime = 0;
int completed = 0;
Node* it = masterList.getHead();
int total = masterList.getSize();
ProcessList completedProcesses;
timeline.clear();
while (completed < total) {
while(it != nullptr && it->data.arrivalTime <= currentTime) {
pq.enqueue(it->data);
it = it->next;
}
if(!pq.isEmpty()) {
if (preemptive) {
Process p = pq.dequeue();
// Log 1-unit slice
Process slice = p;
slice.arrivalTime = currentTime;
slice.burstTime = 1;
timeline.push_back(slice);
p.remainingTime--;
currentTime++;
if(p.remainingTime > 0) pq.enqueue(p);
if(p.remainingTime == 0) {
p.completionTime = currentTime;
p.waitingTime = p.completionTime - p.arrivalTime - p.burstTime;
p.turnaroundTime = p.waitingTime + p.burstTime;
completed++;
completedProcesses.addProcess(p);
}
} else {
Process p = pq.dequeue();
// Log full slice
Process slice = p;
slice.arrivalTime = currentTime;
slice.burstTime = p.burstTime;
timeline.push_back(slice);
p.waitingTime = currentTime - p.arrivalTime;
currentTime += p.burstTime;
p.completionTime = currentTime;
p.turnaroundTime = p.waitingTime + p.burstTime;
completedProcesses.addProcess(p);
completed++;
}
} else {
if(it != nullptr) currentTime = it->data.arrivalTime;
}
}
return completedProcesses;
}
```
=== Starvation Problem and Solutions
*Problem:* Low-priority processes may wait indefinitely if high-priority processes keep arriving.
*Solution - Aging:* Gradually increase the priority of waiting processes over time.
```cpp
// Potential aging implementation (not in current project)
void applyAging(ProcessList& waitingProcesses, int currentTime) {
Node* curr = waitingProcesses.getHead();
while(curr != nullptr) {
int waitTime = currentTime - curr->data.arrivalTime;
// Increase priority every 10 time units
curr->data.priority -= (waitTime / 10);
if(curr->data.priority < 0) curr->data.priority = 0;
curr = curr->next;
}
}
```
#pagebreak()
== Round Robin (RR)
=== Algorithm Overview
Round Robin allocates the CPU to each process for a fixed *time quantum*. If a process doesn't complete within its quantum, it's preempted and moved to the back of the queue. This ensures fair CPU distribution.
=== Characteristics
#table(
columns: (auto, auto),
inset: 8pt,
[*Property*], [*Value*],
[Type], [Preemptive],
[Starvation], [No — guaranteed CPU time for all],
[Fairness], [High — equal time slices for all processes],
[Response Time], [Good for interactive systems],
[Context Switches], [Higher than FCFS],
[Time Quantum Impact], [Critical parameter for performance],
)
=== Time Quantum Selection
The choice of time quantum (Q) dramatically affects performance:
*Too Small (Q → 0):*
- Approaches processor sharing
- Excessive context switch overhead
- Poor throughput
*Too Large (Q → ∞):*
- Degrades to FCFS behavior
- Poor response time
- Loses fairness advantage
*Optimal Range:*
- Typically 10-100 ms in real systems
- Should be larger than context switch time
- Depends on process characteristics
=== Implementation
```cpp
ProcessList Scheduler::roundRobin(ProcessList &masterList, int quantum) {
ProcessQueue readyQueue;
int currentTime = 0;
int completed = 0;
Node* it = masterList.getHead();
int total = masterList.getSize();
ProcessList completedProcesses;
timeline.clear();
while(completed < total) {
// Load arrived processes
while(it != nullptr && it->data.arrivalTime <= currentTime) {
readyQueue.enqueue(it->data);
it = it->next;
}
if(!readyQueue.isEmpty()) {
Process p = readyQueue.dequeue();
int timeToRun = (p.remainingTime < quantum) ? p.remainingTime : quantum;
// Log slice for Gantt Chart
Process slice = p;
slice.arrivalTime = currentTime; // Start Time
slice.burstTime = timeToRun; // Duration
timeline.push_back(slice);
p.remainingTime -= timeToRun;
currentTime += timeToRun;
// Check for new arrivals DURING the time slice
while(it != nullptr && it->data.arrivalTime <= currentTime) {