L2 · Operating systemsHow Computers Work · part 4 of 4

How an Operating System Schedules Work

You have more programs than CPU cores, yet everything seems to run at once. Here's how the scheduler does it.

Takumi Yamada
· 6 min read
operating-systemsschedulingconcurrencygoroutinesgo

Open your laptop's list of running programs. There are hundreds of them, all running at once, on maybe eight . A core is one part of the processor that can run one program at a time.

So they aren't really running at once. The operating system switches between them so quickly that it looks like they are. This is called scheduling, and I think it's one of the best ideas in systems software.

The silicon of a processor seen through a microscope. Eight matching yellow blocks sit in two rows of four, and a large orange area fills the right side.
The chip inside an eight-core processor, an Intel Core i9-9900K, seen through a microscope. Each core is one of the eight matching yellow blocks, four along the top and four along the bottom. The orange area on the right is the graphics part. The scheduler decides which thread runs on each of these eight cores.Photo: Fritzchens Fritz, CC0 1.0, via Wikimedia Commons (original). Changes: cropped and resized.

Processes versus threads

A process is a running program. It has its own memory, its own open files and its own other resources. Two processes can't read each other's memory by accident, because the operating system and the hardware keep them apart.

A thread is one line of work running inside a process. A process can have many threads, and they all share the process's memory. That makes it easy for threads to share data, because they can use the same variable. It also makes threads risky. If two threads change the same data at the same moment, the result can be wrong. This is called a data race, and it's why programs use locks, which let only one thread use the data at a time.

PROCESS Ashared memoryTHREADTHREADisolated from each otherPROCESS Bits own memoryTHREAD
Threads inside one process share its memory. Two processes share nothing.

As a rule of thumb, use separate processes when parts of a system must be kept apart, and threads when one program needs several workers sharing the same data.

The scheduler and context switching

The scheduler is the part of the operating system that decides which runs on which core right now. There are fewer cores than threads, so it gives each thread a short turn. It runs thread A for a few milliseconds, pauses it, runs thread B, and so on.

Pausing one thread and starting another is called a context switch, and it takes three steps.

  1. Save thread A's state, which means the values of all the 's (Central Processing Unit's) , including the program counter and the .
  2. Load thread B's saved state into those registers.
  3. Continue. Thread B carries on exactly where it stopped.
THREAD A, PAUSEDsaved stateONE COREregistersPC, SP and the restTHREAD B, NEXTsaved state1save2load3resume: thread B carries on exactly where it left off
The three steps above, on one core.

A context switch takes between one and five microseconds, and no useful work happens during that time. There is a second cost too. Thread B's data probably isn't in the , because thread A was using the cache. So thread B runs slower until the cache fills up with its data again.

Switching costs time, so a program that causes fewer switches often runs faster.

Preemption: who is in control

Early systems used cooperative scheduling. A thread ran until it chose to give up the CPU. One buggy program stuck in an endless loop could freeze the whole computer.

Modern operating systems are preemptive instead. A hardware timer sends a signal, called an interrupt, every few milliseconds. The interrupt hands control back to the operating system's kernel, and the chooses again. No thread can keep a core forever, because the timer always interrupts it.

COOPERATIVEthreads give wayA: STUCK IN A LOOP, NEVER GIVES WAYthread B is ready, and never gets the corePREEMPTIVEa timer decidesABABABtimer interruptevery few milliseconds, and the scheduler chooses again
The same two threads on one core. In the second row the timer interrupt ends every turn.

The scheduler picks the next thread by priority and by fairness. For example, Linux's Completely Fair Scheduler counts how much CPU time each thread has had, and runs the one that has had the least. Over time, that gives each thread a roughly equal share.

Some threads are waiting for something slow, such as a file from the disk or a from the network. The scheduler sets those threads aside and doesn't run them until their data arrives. That way, a waiting thread doesn't use a core.

READY TO RUNBDpicked nextCORErunning AA reads a fileWAITING, NOT SCHEDULEDCfor the diskwhen its data arrives, C goes back to the queue
A waiting thread is kept out of the queue the scheduler picks from, so it uses no core.

Concurrency versus parallelism

These two words are often used as if they mean the same thing. They don't.

Concurrency means a program is organized to work on many tasks, making progress on each in turns. It works even on a single core.

Parallelism means several tasks are really running at the same instant. It needs more than one core.

CONCURRENCYone core switches between two taskscore 1ABABABPARALLELISMtwo cores run both at the same instantcore 1Acore 2Bthe same work, done in half the timetime
Two tasks of three slices each.

You can have concurrency without parallelism: one core switching between several tasks. You can also have parallelism without much concurrency: one big calculation split across several cores. Good systems are designed for concurrency, and run in parallel whenever the hardware has spare cores.

Go's goroutines: M to N scheduling

This is the part I work with every day.

Operating system threads are fairly heavy. Each one gets a large stack, often several megabytes, and every switch between them goes through the . A hundred thousand operating system threads would overload most machines.

OS THREAD1 MB of its stackGOROUTINE2 KB to start2 KB is this thin line512 goroutine stacks fit in that one megabyte, and a thread's stack is often several megabytes.
One megabyte of a thread's stack next to a new goroutine's stack, to scale.

Go avoids this with goroutines. A goroutine is a task managed by Go itself, not by the operating system. Go runs many goroutines (M of them) on a few operating system threads (N of them), which is why this is called M to N scheduling. Switching between goroutines on the same thread happens inside your program, without asking the kernel.

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 100_000; i++ {
        wg.Add(1)
        go func(id int) {       // a goroutine, not an OS thread
            defer wg.Done()
            work(id)
        }(i)
    }
    wg.Wait() // 100k concurrent tasks, a handful of OS threads
}

Go's scheduler has three parts, each named with one letter.

  • G is a goroutine: the task itself. It has its own small stack, which starts at about 2 KB and grows when needed.
  • M is a machine: an operating system thread that actually runs code.
  • P is a processor: a queue of goroutines that are ready to run. By default there is one P for each core.

An M must hold a P to run goroutines. When a goroutine waits, for example on a , Go sets it aside and runs another goroutine on the same thread. That's cheap, and the kernel isn't involved.

Some calls to the kernel, called system calls, can make the whole thread wait. When a goroutine makes one of those, Go moves its P, with the queue, to another thread. The other goroutines keep running while the first one waits.

BEFOREG1 is about to make a blocking system callPGGGM1OS threadG1DURINGthe P has moved to another threadPM1in a system callG1PGGGM2OS threadThe queued goroutines keep running, on M2.
A blocking system call ties up the thread, not the P. The runtime moves the P and its queue to a thread that can run.

If a P runs out of work, it takes goroutines from another P's queue. This is called work stealing, and it keeps all the cores busy.

Pholds a run queueMOS threadCOREGGGGrunningqueuedPholds a run queueMOS threadCOREGGstolenrunningidle P stealsPARKEDGblocked ona channel
Two Ps. The second has run out of goroutines and takes one from the first.

The result is that switching between goroutines is cheap, and their stacks start small. That's why a Go can handle hundreds of thousands of connections at once, with one goroutine for each. With one operating system thread per connection, it would run out of memory long before that.

Since Go 1.14, Go's scheduler is also preemptive. A goroutine stuck in a long calculation can't keep the others from running. It's the same problem operating system schedulers solved, solved again one level higher.

Why the mental model pays off

The operating system's scheduler and Go's scheduler are the same idea at two levels. Both have a limited number of cores and more work than cores. Both switch between tasks fast enough that the tasks seem to run at the same time. And both are preemptive, so no task can keep a core to itself.

Knowing this helps with real decisions. You can choose how many cores Go uses. You can understand why a slow call into C code ties up a whole operating system thread. And you can tell when an extra will make a program faster by using another core, and when it only adds one more task to take turns.

Check yourself

3 questions · nothing is saved
  1. 1.What makes a modern operating system preemptive?
  2. 2.One core switching between several tasks, making progress on each in turn, is…
  3. 3.A goroutine makes a system call that blocks its whole thread. What does Go do?

Who wrote this

Author profile and background

Takumi Yamada

Takumi Yamada

· Backend Engineer

Backend engineer building services, databases, Linux tooling, and NEGEN SYSTEMS. Writing about low-level mechanics, distributed systems, and real-world security.

End of post
NEGEN SYSTEMS
Receipt · post 10 of 31
Written
Jan 1, 2026
Length
1,215 words · 6 min
Built
…
Served by
…
Delivered
…
Over the wire
…
Go's share
…
Next up the stack · L2 Operating systems

Building a Home Server From an Old Laptop

Turning a spare laptop into a Debian home server: choosing the operating system, setting it up remotely without locking yourself out, publishing services through a Cloudflare Tunnel, and fixing an AdGuard Home container that ran but couldn't be reached.

13 min read
From other series