|
| 1 | +""" |
| 2 | +Simple Implementation of the FCFS CPU scheduling algorithm |
| 3 | +FCFS is a non-preemptive CPU scheduling algorithm that |
| 4 | +schedules processes based on their arrival time. |
| 5 | +https://www.geeksforgeeks.org/program-for-fcfs-cpu-scheduling-set-1/ |
| 6 | +Author: [Madhav Goyal](https://github.com/mdhvg) |
| 7 | +""" |
| 8 | + |
| 9 | + |
| 10 | +def fcfs(processes: list[tuple[int, int, int]]) -> None: |
| 11 | + """ |
| 12 | + Function to implement the FCFS CPU scheduling algorithm |
| 13 | +
|
| 14 | + processes: list of tuples where each tuple contains the |
| 15 | + process_id, arrival_time and burst_time of each process |
| 16 | + """ |
| 17 | + n = len(processes) |
| 18 | + processes.sort(key=lambda x: x[1]) |
| 19 | + waiting_times = [0] * n |
| 20 | + total_waiting_time = 0 |
| 21 | + |
| 22 | + for i in range(1, n): |
| 23 | + waiting_times[i] = processes[i - 1][2] + waiting_times[i - 1] |
| 24 | + total_waiting_time += waiting_times[i] |
| 25 | + |
| 26 | + print(f"Average Waiting Time: {total_waiting_time / n}") |
| 27 | + |
| 28 | + """ |
| 29 | + Printing the Gantt Chart for the processes in the FCFS order |
| 30 | + The - and * symbols are used to represent the burst time and |
| 31 | + idle time respectively for each process. |
| 32 | + """ |
| 33 | + last_burst = 0 |
| 34 | + for i in range(n): |
| 35 | + print("-" * last_burst, end="") |
| 36 | + print("*", end="") |
| 37 | + last_burst = processes[i][2] |
| 38 | + print("-" * last_burst, end="") |
| 39 | + print("\n", end="") |
| 40 | + |
| 41 | + last_burst = 0 |
| 42 | + for i in range(n): |
| 43 | + print(" " * last_burst, end="") |
| 44 | + print(f"{processes[i][0]}", end="") |
| 45 | + last_burst = processes[i][2] |
| 46 | + print("\n", end="") |
| 47 | + |
| 48 | + |
| 49 | +def main(): |
| 50 | + """ |
| 51 | + Main function to demonstrate the FCFS CPU scheduling algorithm |
| 52 | + pass an array of (process_id, arrival_time, burst_time) to fcfs |
| 53 | + >>> processes = [(1, 0, 3), (2, 1, 5), (3, 2, 2), (4, 3, 7), (5, 2, 2)] |
| 54 | + >>> fcfs(processes) |
| 55 | + Average Waiting Time: 6.6 |
| 56 | + *---*-----*--*--*------- |
| 57 | + 1 2 3 5 4 |
| 58 | + """ |
| 59 | + processes = [(1, 0, 3), (2, 1, 5), (3, 2, 2), (4, 3, 7), (5, 2, 2)] |
| 60 | + fcfs(processes) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + main() |
| 65 | + import doctest |
| 66 | + |
| 67 | + doctest.testmod() |
0 commit comments