← Lessons

quiz vs the machine

Silver1120

Concurrency

The Goroutines Model

How Go multiplexes cheap goroutines onto OS threads and communicates through channels.

5 min read · intro · beat Silver to climb

Goroutines as cheap tasks

A goroutine is Go's lightweight thread of execution. Starting one costs little, so a program can spawn many thousands. The Go runtime multiplexes these goroutines onto a smaller set of OS threads automatically.

The G M P pieces

Go's scheduler names three parts:

  • G is a goroutine, the work to run.
  • M is a machine thread, a real OS thread that executes code.
  • P is a processor, a scheduling context that holds a queue of runnable goroutines and must be held by an M to run Go code.

The number of P values is set by a runtime variable, capping how many goroutines run truly in parallel.

Communicating by channels

Go encourages sharing data by passing it over channels rather than locking shared memory. A channel is a typed conduit: one goroutine sends a value, another receives it. A send on an unbuffered channel blocks until a receiver is ready, which synchronizes the two goroutines at that moment.

Key idea

Go runs many cheap goroutines over few OS threads using G M P scheduling and prefers passing data through channels over locking shared memory.

Check yourself

Answer to earn rating on the learn ladder.

1. In Go's scheduler, what does a P represent?

2. What happens on a send to an unbuffered channel?