How does a preemptive scheduler manage a thread's timeslice?
Rob Edmondson The lowest level preemptive scheduler (kernel layer) uses the system timer interrupt and context switching to manage timeslices. When any CPU interrupt occurs, the CPU makes a note of where it was, and what it was doing (pushes all registers onto the stack). The CPU then processes the interrupt and returns to what it was previously doing (pops all registers from the stack). The thread context in this sense, is the information the CPU needs to start or resume execution in any section of code. The scheduler is invoked by the timer interrupt routine (it can also be part of the timer interrupt). The scheduler checks to see if the current timeslice has expired; if so, the current thread context is stored and the next valid thread context is restored. The most basic implementation is a stack swap, as each thread has its own stack. When a thread is created, it gets a new context with an empty stack. The new context directs the CPU to the thread's run() member at the beginning of its timeslice. A thread's context is destroyed when the thread returns from the run() member, or its stop() member is successfully invoked.