How exactly does a CPU do process scheduling? I know in theory how various scheduling algorithms work, such as round robin, where each process is given small time slices to run a few instructions, before the operating system passes execution onto the next process, and so on.

What I don't understand is how this is possible. The operating system is just some code, and so are all of the processes, so why doesn't this happen?


OS passes execution to the first process.
Now that process is running, the OS can't stop it, since the CPU can only run one instruction at a time, and that instruction is the process'.
Now the operating system has no control over the process, and can't stop it.


Now obviously this doesn't happen, but why not? How would the operating system say something like "Okay, you can run 3 instructions now, but after that let the other process run"?
The operating system arranges for periodic timer interrupts, which only it can handle, so it periodically regains control of the CPU without requiring the co-operating of any other process. Also, when a process tries to access the hardware, that is mediated by the operating system, which gives it another opportunity to decide which process to run next.