Here’s an ELI5 (Explain Like I’m 5) version of what the scheduler() function in xv6 is doing:
What is a scheduler?
Imagine a classroom with a bunch of students (processes) but only one teacher (CPU). The teacher can only help one student at a time, so she needs a way to pick which student to help next. That’s what the scheduler does — it chooses which process gets to use the CPU next.
Code Walkthrough
Here’s the code we’re talking about:
|
|
What’s happening step-by-step?
|
|
This is the main loop for choosing and running processes. It runs forever.
The two-line style is a nod to older Unix/C practices, emphasizing readability on narrow terminals and clean vertical formatting (the names of functions are always at the start of lines). It’s not required by the language, just a style that’s still respected in minimalist or historically-inspired codebases like xv6.
In most modern C you would see:
|
|
Which is more compact and familiar to today’s programmers.
Setup
|
|
- We get the current CPU (c) that’s doing the scheduling.
- We say: “You’re not running any process yet.”
Loop forever
|
|
This is an infinite loop: we’ll keep checking for runnable processes forever.
Allow interruptions
|
|
This turns on interrupts, letting the CPU respond to things like keyboard input, timers, etc.
Lock the process table
|
|
We’re about to look at the list of processes, so we lock it so no one else changes it while we’re looking.
Search for a process to run
|
|
We go through each process in the system. If it’s not ready to run, we skip it.
🏃♂️ Run it!
If it is runnable:
|
|
We:
- Say “this CPU is now running process p”
- Set up its memory
- Switch the CPU to actually run it
- When it’s done (e.g. goes to sleep or gives up control), we come back
- Mark the CPU as not running anything now
💤 Nothing to do? Go to sleep.
|
|
If we didn’t find any process to run, we:
- Unlock the process table
- Allow interrupts
- Use the hlt instruction to put the CPU to sleep until something wakes it (like a timer or input)
This saves CPU power instead of spinning in a loop doing nothing.
Unlock and repeat
|
|
If we ran something or not, we unlock the process table and go back to the top of the loop.
Summary:
This function:
- Loops forever
- Looks through all processes to find one ready to run
- Switches to that process
- Sleeps the CPU if nothing is ready
- Repeats