Round Robin Scheduler
Round Robin Scheduler
Simulate one CPU serving tasks in FIFO round robin order. Track arrivals, remaining bursts, and handoff overhead to compute each completion time.
Types
type Task struct {
ID int
Arrival int
Burst int
}
type Result struct {
Completion map[int]int // task ID -> completion time
TotalTime int
}
func RoundRobin(tasks []Task, quantum int, context int) Result
Rules
- Time starts at 0.
- Tasks are enqueued in order of arrival time, breaking ties by input order.
- If the ready queue is empty, time jumps to the next task arrival.
- Each task runs for
min(quantum, remaining). - At a slice end, enqueue all arrivals through that time before putting an unfinished running task at the tail. Arrivals exactly at the boundary are included.
- If a task finishes, record its completion time before charging any subsequent handoff.
- If a task is preempted and no other task is ready, it continues with no context switch cost.
- If another task is ready at the slice end, add
contexttime before the next task runs. Arrivals during this interval join after tasks already queued; they do not restart the interval. - If a finished task leaves an empty queue, jump to the next arrival with no context switch cost. Do not charge after the final completion.
Worked example
For tasks [{ID:1, Arrival:0, Burst:5}, {ID:2, Arrival:1, Burst:2}, {ID:3, Arrival:3, Burst:1}], quantum 2, context 1:
0–2 task 1; 2–3 switch; 3–5 task 2; 5–6 switch;
6–8 task 1; 8–9 switch; 9–10 task 3; 10–11 switch; 11–12 task 1
Return Completion={1:12, 2:5, 3:10} and TotalTime=12. At time 2, queue order is [2,1]; task 3 arrives during the handoff and joins behind both.
Notes
- Ignore tasks with non-positive burst.
- Task IDs are unique, arrivals are nonnegative,
quantum > 0, andcontext >= 0. Inputs and accumulated times fit inint. - Do not change the input tasks. There is no I/O blocking or mid-slice arrival preemption.
- If no tasks have positive bursts, return an empty completion map and total time 0.
Run tests to see results
No issues detected