Loading...
Loading...
In operating systems, processes and threads are fundamental units of execution. A process is an independent program in execution with its own memory space, while a thread is a lightweight unit within a process that shares the same memory. Context switching is the mechanism by which a CPU saves the state of a currently running task and restores the state of the next task to be executed.
Your task is to simulate a simplified round-robin task scheduler that models context switching between threads sharing a process's resources.
You are given n threads (belonging to the same process, thus sharing memory), each with a burst time (the total CPU time it needs). The scheduler uses a round-robin algorithm with a fixed time quantum q. Each thread runs for at most q units before a context switch occurs. A context switch itself costs switchCost units of time.
Return an array of integers representing the completion time of each thread in their original order (0-indexed).
burstTimes: an array of integers where burstTimes[i] is the burst time of thread iquantum: an integer representing the time slice each thread gets per roundswitchCost: an integer representing the cost of each context switch in time unitsReturn an integer array completionTimes where completionTimes[i] is the time at which thread i finishes execution.
Input: burstTimes = [4, 3, 5], quantum = 2, switchCost = 1
Output: [10, 9, 16]
Explanation:
A queue-based simulation gives: [10, 9, 16]
Input: burstTimes = [5, 5], quantum = 5, switchCost = 0
Output: [5, 10]
Explanation: Each thread gets a full quantum. Thread 0 finishes at t=5, Thread 1 at t=10. No switch cost, so no overhead.
Input: burstTimes = [1], ,
Only one thread exists. It runs for its burst time (1 unit), finishes at t=1. No context switch needed.
1 <= n <= 10^4 1 <= burstTimes[i] <= 10^4 1 <= quantum <= 10^4 0 <= switchCost <= 100
quantum = 3switchCost = 2[1](threadIndex, remainingTime).currentTime variable. Each iteration, dequeue a thread, run it for min(quantum, remaining) units, then add switchCost only if there are more threads waiting.