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.