These are the notes for Go episode 43, the first episode of the concurrency part of the course. Raju's chai stall gets five orders at once, and a program that makes them one after another takes 5 seconds, mostly spent waiting. So you invent the goroutine: one word, go, starts a function and does not wait for it. Then the surprise that when main returns, the program ends, why time.Sleep is the wrong way to wait, a first look at sync.WaitGroup, how goroutines differ from OS threads (100,000 of them, measured), concurrency vs parallelism, runtime.GOMAXPROCS, runtime.NumCPU, runtime.Gosched, and the idea behind it all: CSP and share memory by communicating.
All outputs and errors here are from real runs (Go 1.24.7, linux/amd64, a machine with 2 CPUs). Timings change on every run, and the order of lines printed by goroutines changes too: that is normal, and part of the lesson. Every program is a plain main.go: run it in the SyntaxPilot compiler, or on your computer with go run main.go.
Facts and sources
- The Go specification (Go 1.24.7,
doc/go_spec.html), Go statements: "A "go" statement starts the execution of a function call as an independent concurrent thread of control, or goroutine, within the same address space." Program execution: whenmainreturns, "the program exits. It does not wait for other (non-main) goroutines to complete." - Go 1.4 release notes (go.dev/doc/go1.4): "the default starting size for a goroutine's stack in 1.4 has been reduced from 8192 bytes to 2048 bytes."
- Rob Pike, "Concurrency is not Parallelism" (go.dev/blog/waza-talk, slides): "This talk was presented at Heroku's Waza conference in January 2012." "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once." Concurrency is "the composition of independently executing processes"; parallelism is "the simultaneous execution of (possibly related) computations".
- Rob Pike, "Go Concurrency Patterns" (2012, slides): Go's concurrency has its roots in "Hoare's CSP in 1978". A goroutine "is not a thread", it is "very cheap", and "It's practical to have thousands, even hundreds of thousands of goroutines." Goroutines are "multiplexed dynamically onto threads as needed to keep all the goroutines running."
- "Share Memory By Communicating" (go.dev/blog/codelab-share), quoting Effective Go: "Do not communicate by sharing memory; instead, share memory by communicating."
go doc runtime.GOMAXPROCS(Go 1.24.7): "GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. It defaults to the value of runtime.NumCPU. If n < 1, it does not change the current setting."go doc runtime.Gosched: "Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically."go doc runtime.NumGoroutine: "NumGoroutine returns the number of goroutines that currently exist."- Go 1.14 release notes (tip.golang.org/doc/go1.14): "Goroutines are now asynchronously preemptible."
- Go 1.22 release notes (golang.google.cn/doc/go1.22): "In Go 1.22, each iteration of the loop creates new variables, to avoid accidental sharing bugs."
- The 8 MB thread stack is measured on the machine that made this episode:
ulimit -sprinted8192(kilobytes), the usual Linux default. Other systems use other sizes.
The problem: one order at a time (rush hour at Raju's chai stall)
At 4 PM the office next door goes on break and five customers order chai at once. Each cup needs about a minute on the stove. Raju's new helper puts one pan on, stands and watches it boil, and only then starts the next. Customer 1 gets chai after 1 minute, customer 5 after 5 minutes. And the stove has four burners, three of them off. The helper isn't busy; he's waiting.
The same helper as a program. time.Sleep(time.Second) pauses for one second: our "boiling time". time.Now() reads the clock and time.Since(start) says how much time has passed (episode 36); .Round(time.Second) rounds it to whole seconds.
package main
import (
"fmt"
"time"
)
// makeChai: the cook puts the pan on and waits 1 second
func makeChai(order int) {
time.Sleep(time.Second)
fmt.Println("order", order, "ready")
}
func main() {
start := time.Now()
for i := 1; i <= 5; i++ {
makeChai(i)
}
fmt.Println("all done in", time.Since(start).Round(time.Second))
}
Output (real run):
order 1 ready
order 2 ready
order 3 ready
order 4 ready
order 5 ready
all done in 5s
Why so slow? A normal function call means "do this, and I'll wait right here until you're finished". The program runs sequentially: one step after another, each step starting only when the previous one has finished. Almost all of those 5 seconds the program did nothing: it waited. In real programs the waiting is a network call, a database query, reading a file. A program that spends its time waiting is called I/O-bound (I/O = input/output); one that spends its time computing is CPU-bound.
The fix: the go statement (put the pan on, move on)
| At the chai stall | In Go |
|---|---|
| Watch one pan until it boils, then start the next | a normal call makeChai(i): wait until it returns |
| Put a pan on a burner and move straight on | the go statement go makeChai(i): start it, don't wait |
| Each pan boils on its own, independent of the others | a goroutine: a function running on its own |
Write go in front of a function call and Go starts the function and does not wait for it: the line finishes at once and your code moves on. The function keeps running by itself, side by side with the rest of the program. That running function is a goroutine. The Go spec calls it "an independent concurrent thread of control": in plain words, a function call that runs by itself, at the same time as everything else.
for i := 1; i <= 5; i++ {
go makeChai(i)
}
The full program is the one above with that one word added. Output (real run):
all done in 0s
No orders at all!
When main returns, the program ends
main itself runs in a goroutine too: the main goroutine. When the main function returns, the whole program ends, at once. The spec: it "does not wait for other (non-main) goroutines to complete". Our loop started five goroutines in a few microseconds, printed "all done in 0s" and returned, so the five goroutines were killed before their one-second sleep was over. Nothing tells you this happened: no error, no warning, just missing work.
Waiting the wrong way: time.Sleep
The obvious patch: make main sleep long enough. Each order takes 1 second, so sleep 2 to be safe. But order 5 is masala chai, which takes 3 seconds. A time.Duration (episode 36) is a length of time; 3*time.Second is three seconds.
package main
import (
"fmt"
"time"
)
func makeChai(order int, d time.Duration) {
time.Sleep(d)
fmt.Println("order", order, "ready")
}
func main() {
start := time.Now()
for i := 1; i <= 4; i++ {
go makeChai(i, time.Second)
}
go makeChai(5, 3*time.Second) // masala chai: slower
time.Sleep(2 * time.Second) // guess: 2 s is enough?
fmt.Println("all done in", time.Since(start).Round(time.Second))
}
Output (real run; orders 1-4 come in a different order on each run):
order 4 ready
order 1 ready
order 2 ready
order 3 ready
all done in 2s
Orders 1 to 4 came in a mixed order because they really ran at the same time, and whichever goroutine woke first printed first. Order 5 is missing: main slept 2 s, the masala chai needed 3 s, and the program ended under it.
Why sleeping is wrong: it's a guess. Too short and you lose work (as here); too long and you waste time on every run; on a slow or busy machine even a good guess fails sometimes. We don't want to wait for a fixed time; we want to wait until the work is done.
A first look at sync.WaitGroup
The real fix gets its own episode (episode 45); here is a preview. A sync.WaitGroup is a counter of unfinished jobs, like a token board at the counter: you go home when every token has been collected.
wg.Add(1): one more job (call it before starting the goroutine).wg.Done(): this job is finished (counter minus one).defer(episode 10) makes sure it runs when the function ends.wg.Wait(): block until the counter is back to 0.
package main
import (
"fmt"
"sync"
"time"
)
func makeChai(order int, d time.Duration) {
time.Sleep(d)
fmt.Println("order", order, "ready")
}
func main() {
start := time.Now()
var wg sync.WaitGroup // a counter of unfinished jobs
for i := 1; i <= 5; i++ {
d := time.Second
if i == 5 {
d = 3 * time.Second // masala chai: slower
}
wg.Add(1)
go func() {
defer wg.Done()
makeChai(i, d)
}()
}
wg.Wait() // wait until the counter is 0
fmt.Println("all done in", time.Since(start).Round(time.Second))
}
Output (real run; the first four lines come in any order):
order 2 ready
order 4 ready
order 3 ready
order 1 ready
order 5 ready
all done in 3s
All five orders, in 3 seconds: the time of the slowest order, not the sum of all of them. Five customers served in the time of one slow cup. You just invented goroutines.
Two details in this program:
go func() { ... }()starts an anonymous function (a function literal, episode 10) as a goroutine. The()at the end calls it.- The goroutine uses the loop variables
iandd. Since Go 1.22 each loop iteration has its owni(episode 8), so every goroutine sees its own order number. (Before Go 1.22 all goroutines shared onei, a famous bug.)
The other way to wait is a channel: a typed pipe that one goroutine sends values into and another receives from. Channels get episodes 47 and 48.
Common slip: go without the call
package main
import "fmt"
func main() {
go func() {
fmt.Println("order ready")
}
}
Real compiler error:
# command-line-arguments
./main.go:6:8: expression in go must be function call
Without the final (), the function is only described, never called. go needs a call: go func() { ... }(), or go makeChai(1). Writing go makeChai (no brackets) gives the same error.
Goroutines vs OS threads (hiring cooks vs writing order slips)
| In a restaurant | In a computer |
|---|---|
| Hire a full-time cook: own counter space, slow to hire | an OS thread: made by the operating system, with a big stack |
| Write an order slip: one small piece of paper | a goroutine: made by Go, starts with a 2 KB stack |
| A head cook hands slips to a few real cooks | the Go runtime scheduler runs many goroutines on a few threads (multiplexing) |
- The operating system (OS) is the program that runs your computer and shares it among programs: Linux, Windows, macOS.
- A thread (OS thread) is a worker the operating system schedules on a CPU. Most languages (Java, C++, Python) use threads to run work at the same time. Creating one asks the OS, and each one gets its own stack.
- A stack is the memory where a running function keeps its local variables and where it must return to. Each thread, and each goroutine, has its own.
- A goroutine is created and managed by Go's runtime (the part of Go that runs inside every Go program: scheduler, garbage collector, memory). Since Go 1.4 a goroutine starts with a 2,048-byte (2 KB) stack, which grows automatically when a function needs more (and can shrink again).
- Multiplexing: sharing a few things (threads) among many users (goroutines). When a goroutine waits, its thread picks up another goroutine. How exactly: episode 44.
Measuring it: start 100,000 goroutines, each just waiting 2 seconds. runtime.NumGoroutine() counts the goroutines that exist right now. runtime.ReadMemStats(&m) fills a runtime.MemStats with memory statistics; m.StackInuse is the bytes used by stacks. (100_000 is 100000; underscores in numbers are only for reading, episode 4.)
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
var m runtime.MemStats
fmt.Println("goroutines at start:", runtime.NumGoroutine())
start := time.Now()
for i := 0; i < 100_000; i++ {
go func() {
time.Sleep(2 * time.Second) // a waiting customer
}()
}
fmt.Println("started 100,000 in", time.Since(start).Round(time.Millisecond))
fmt.Println("goroutines now:", runtime.NumGoroutine())
runtime.ReadMemStats(&m)
fmt.Println("stack memory:", m.StackInuse/1024/1024, "MB")
fmt.Println("per goroutine:", m.StackInuse/100_000, "bytes")
}
Output (real run; the start time changes):
goroutines at start: 1
started 100,000 in 177ms
goroutines now: 100001
stack memory: 195 MB
per goroutine: 2050 bytes
- At the start: 1 goroutine, the main goroutine.
- 100,000 goroutines started in a fraction of a second.
- 100,001 now: ours plus main.
- About 195 MB of stacks: about 2 KB each, as the Go 1.4 notes promise.
Compare threads. On this Linux machine ulimit -s prints 8192: a new thread's stack is 8 MB by default, 4,096 times bigger than 2 KB. 100,000 threads would reserve about 800 GB of address space (the OS reserves it and fills it in only as it is used, but it's still a big reservation, plus a system call to create each one). That's why the Go team says it's practical to have hundreds of thousands of goroutines.
The homework version with 1,000,000 goroutines (each sleeping 10 s so none finishes early) printed, in a real run:
goroutines at start: 1
started 1,000,000 in 2.592s
goroutines now: 1000001
stack memory: 1953 MB
per goroutine: 2048 bytes
A million goroutines: about 2 GB. Cheap per goroutine, but not free: don't start unlimited goroutines for unlimited work (worker pools fix that, episode 52).
Concurrency vs parallelism (one cook juggling vs two cooks cooking)
| In the kitchen | In a program |
|---|---|
| One cook, five pans: switches between them, never idle | concurrency: dealing with many things at once |
| Two cooks at two stoves, cooking at the same instant | parallelism: doing many things at once |
| A kitchen plan with stations: works with one cook or with ten | a concurrent design: parallelism is a bonus |
Rob Pike, one of Go's creators, at Heroku's Waza conference in January 2012: "Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once."
- Concurrency is about structure: the program is made of independent pieces (goroutines) that can make progress without waiting for each other. Even one pair of hands can juggle them.
- Parallelism is about execution: pieces really running at the same instant. That needs more than one CPU core.
- A CPU (central processing unit) is the chip that runs instructions. A core is one processing unit inside it: one "pair of hands". This machine has 2 cores.
A concurrent design works on one core and gets faster when more cores are available. Goroutines give you the structure; Go's runtime adds parallelism when the machine has cores.
runtime.NumCPU and runtime.GOMAXPROCS
runtime.NumCPU()returns how many CPU cores Go can use.runtime.GOMAXPROCS(n)sets the maximum number of CPUs running Go code at the same moment and returns the previous setting. The default isNumCPU.GOMAXPROCS(0)(any n < 1) only asks, without changing anything. It can also be set with the environment variableGOMAXPROCS=1 go run main.go.
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
func main() {
fmt.Println("CPUs:", runtime.NumCPU())
fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0)) // 0 = just ask
runtime.GOMAXPROCS(1) // only ONE goroutine runs at a time now
start := time.Now()
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(time.Second) // waiting needs no CPU
}()
}
wg.Wait()
fmt.Println("5 chai orders on 1 CPU:", time.Since(start).Round(time.Second))
}
Output (real run):
CPUs: 2
GOMAXPROCS: 2
5 chai orders on 1 CPU: 1s
With only one CPU allowed, five waiting orders still finish in 1 second, not 5. That is concurrency without parallelism: a sleeping (waiting) goroutine needs no CPU, so one core keeps all five going.
CPU-bound work needs cores
count is pure CPU work: two billion additions and no waiting, like a cook chopping nonstop. Two goroutines run count, first with GOMAXPROCS 1, then 2.
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
// count: pure CPU work, no waiting at all
func count() {
n := 0
for i := 0; i < 2_000_000_000; i++ {
n += i % 7
}
_ = n
}
func main() {
for _, procs := range []int{1, 2} {
runtime.GOMAXPROCS(procs)
start := time.Now()
var wg sync.WaitGroup
for j := 0; j < 2; j++ {
wg.Add(1)
go func() { defer wg.Done(); count() }()
}
wg.Wait()
fmt.Println("GOMAXPROCS", procs, "->", time.Since(start).Round(100*time.Millisecond))
}
}
Output (real run on a quiet machine):
GOMAXPROCS 1 -> 1.5s
GOMAXPROCS 2 -> 800ms
On 1 core the two jobs take turns; on 2 cores they run at the same time, close to half the time. The numbers change on every run, and the gap shrinks when the machine is busy with other work (other runs printed 1.5s and 1.4s while the CPUs were loaded). Lessons:
- I/O-bound (waiting) work benefits from goroutines even on one core.
- CPU-bound work gets faster only with more cores. More goroutines than cores won't make chopping faster.
runtime.Gosched (you go now)
With GOMAXPROCS(1) there is one cook. main starts a helper goroutine that prints helper 1..3, then prints main 1..3 itself:
package main
import (
"fmt"
"runtime"
)
func say(who string) {
for i := 1; i <= 3; i++ {
fmt.Println(who, i)
}
}
func main() {
runtime.GOMAXPROCS(1) // one cook
go say("helper")
say("main")
}
Output (real run, the usual result):
main 1
main 2
main 3
No taking turns: main kept the only CPU, finished, returned, and the helper never got a turn. (Rarely, about once in a few hundred runs on a busy machine, the helper runs first instead and prints its three lines before main's. Either way, one runs straight through.)
runtime.Gosched() means "I'm not done, but let someone else run for a bit" (the name: Go scheduler). It yields the processor: the current goroutine steps aside and continues later by itself.
package main
import (
"fmt"
"runtime"
)
func say(who string) {
for i := 1; i <= 3; i++ {
fmt.Println(who, i)
runtime.Gosched() // "you go now": let others run
}
}
func main() {
runtime.GOMAXPROCS(1) // one cook
go say("helper")
say("main")
}
Output (real run):
main 1
helper 1
main 2
helper 2
main 3
helper 3
They alternate. In real code you almost never call Gosched yourself: since Go 1.14 the scheduler can preempt (interrupt) a busy goroutine to give others a turn, and with more than one core they run in parallel anyway. Episode 44 opens up the scheduler.
CSP: share memory by communicating (the order window)
Goroutines bring a new problem. Imagine every helper updating one shared tally board of cups sold, all at once. Two helpers rub out 41 and write 42 at the same moment: two cups sold, the board went up by one. When goroutines change the same memory at the same time without coordination, updates get lost: that is a race condition (episodes 45 and 46 show and fix them, and the -race detector catches them).
Go's preferred answer: don't share the board. Pass order slips through a window, so each slip has one owner at a time. Effective Go: "Do not communicate by sharing memory; instead, share memory by communicating." The window is a channel (episode 47).
- Sharing memory to communicate: many goroutines read and write the same variable, protected by locks (a mutex, episode 45).
- Communicating to share memory: a goroutine owns the data and sends it (or a result) to another through a channel; whoever receives it now owns it.
The idea comes from CSP, Communicating Sequential Processes, a 1978 paper by C. A. R. (Tony) Hoare: programs built from sequential processes (each doing one thing at a time) that cooperate only by sending messages to each other. Go's goroutines (the processes) and channels (the messages) are built on that idea. Go also has locks (package sync), and sometimes they are simpler; episode 54 gives a mutex-vs-channel guide.
Mini project: a price checker
Raju buys milk every morning. Four suppliers each take 0.6 to 1.2 seconds to answer with a price (we pretend with time.Sleep).
- Check them one by one and time it.
- Start one goroutine per supplier, each writing only its own slot of a slice (so no two goroutines write the same memory), and wait with a
WaitGroup. - Print the cheapest supplier and
runtime.NumGoroutine()while they run.
Solution
package main
import (
"fmt"
"runtime"
"sync"
"time"
)
// supplier is one milk supplier and how long its price check takes.
type supplier struct {
name string
delay time.Duration
price int
}
// checkPrice pretends to call the supplier over the network.
func checkPrice(s supplier) int {
time.Sleep(s.delay) // waiting for the reply: no CPU needed
return s.price
}
func main() {
suppliers := []supplier{
{"Dairy A", 800 * time.Millisecond, 56},
{"Dairy B", 1200 * time.Millisecond, 54},
{"Dairy C", 600 * time.Millisecond, 52},
{"Dairy D", 1000 * time.Millisecond, 50},
}
// 1. one after another
start := time.Now()
for _, s := range suppliers {
fmt.Println(s.name, "Rs", checkPrice(s))
}
fmt.Println("sequential:", time.Since(start).Round(100*time.Millisecond))
// 2. all at once, one goroutine per supplier
start = time.Now()
prices := make([]int, len(suppliers)) // each goroutine writes only its own slot
var wg sync.WaitGroup
for i, s := range suppliers {
wg.Add(1)
go func() {
defer wg.Done()
prices[i] = checkPrice(s)
}()
}
fmt.Println("goroutines running:", runtime.NumGoroutine())
wg.Wait()
best := 0
for i := range prices {
if prices[i] < prices[best] {
best = i
}
}
fmt.Println("cheapest:", suppliers[best].name, "Rs", prices[best])
fmt.Println("concurrent:", time.Since(start).Round(100*time.Millisecond))
}
Output (real run):
Dairy A Rs 56
Dairy B Rs 54
Dairy C Rs 52
Dairy D Rs 50
sequential: 3.6s
goroutines running: 5
cheapest: Dairy D Rs 50
concurrent: 1.2s
Sequential time = the sum of the delays (0.8 + 1.2 + 0.6 + 1.0 = 3.6 s); concurrent time = the slowest one (1.2 s). 5 goroutines: main plus the four checkers. Writing prices[i] from different goroutines is safe because each goroutine writes a different element, and wg.Wait() makes the writes visible to main before it reads them (episode 46 explains why).
Common mistakes (and the real messages)
| Mistake | Real message / result | Why | Fix |
|---|---|---|---|
main returns right after go f() |
all done in 0s and no orders printed |
main returning ends the program |
wait with a WaitGroup or a channel |
time.Sleep(2 * time.Second) to wait |
order 5 never printed | a guess, not a wait | wait until the work is done |
go func() { ... } without () |
expression in go must be function call |
the function is described, not called | go func() { ... }() |
go makeChai |
expression in go must be function call |
no call | go makeChai(1) |
p := go price() |
syntax error: unexpected keyword go, expected expression |
a go statement returns nothing | send the result back on a channel, or write it to a slot |
runtime.GOMAXPROCS() |
not enough arguments in call to runtime.GOMAXPROCS / have () / want (int) |
it takes an int |
runtime.GOMAXPROCS(0) to ask |
| many goroutines change one variable | lost updates, a different total each run | a race condition | channels, or a mutex (episodes 45-47) |
| expecting goroutine output in a fixed order | lines in a different order each run | goroutines run independently | don't rely on order; collect results by index |
| more goroutines for CPU-heavy work | not faster beyond the number of cores | CPU work needs cores | about one busy goroutine per core |
Practice
- (Homework) Build the price checker (solution above).
- (Homework) Start 1,000,000 goroutines and measure
StackInuse. Why must each goroutine sleep longer than it takes to start them all? - (Homework) Run the
countprogram withGOMAXPROCS1 and 2, three times each. What changes, and why? - Change the
go makeChai(i)program somainwaits correctly withouttime.Sleep. - Predict the output of the
Goschedprogram withGOMAXPROCS(1)and theGoschedcall removed fromsay. Then run it.
Solution 2
The program in the notes (with 1_000_000 and time.Sleep(10 * time.Second)) printed goroutines now: 1000001, stack memory: 1953 MB, per goroutine: 2048 bytes. Starting a million goroutines took about 2.6 s on this machine; with a 2-second sleep, the earliest goroutines finished before the last were started, so a first try printed goroutines now: 874142. Each must outlive the whole start loop to be counted.
Solution 3
With GOMAXPROCS 1 the two jobs share one core, so the time is about the sum of both. With 2 they run in parallel, close to half on a quiet machine. The exact numbers vary because other programs also use the CPUs.
Solution 4
Use the WaitGroup version: var wg sync.WaitGroup, wg.Add(1) before each go, defer wg.Done() in the goroutine, wg.Wait() before printing "all done". It prints all five orders and all done in 1s.
Solution 5
It is the "no taking turns" program: usually only main 1, main 2, main 3. main keeps the only CPU and the program ends when it returns.
Quick quiz
1. runtime.GOMAXPROCS(1), then five goroutines each time.Sleep(time.Second), with a WaitGroup to wait for them. How long does it take? (From the video.)
A. about 1 second · B. about 5 seconds · C. about 0 seconds · D. it never finishes
Answer
A. Sleeping goroutines need no CPU, so one core keeps all five waits going at the same time. Concurrency without parallelism (see the GOMAXPROCS program above: 5 chai orders on 1 CPU: 1s).
2. What does the program with go makeChai(i) and no waiting print?
Answer
Only all done in 0s: main returns and the program ends before any goroutine finishes.
3. Concurrency or parallelism: one cook keeping five pans going?
Answer
Concurrency (dealing with many things at once). Two cooks at two stoves is parallelism.
4. How big is a new goroutine's stack, and since which Go version?
Answer
2 KB (2,048 bytes), since Go 1.4; it grows when needed.
Interview questions
- What is a goroutine? A function executing independently and concurrently with the rest of the program, started by a
gostatement, managed by the Go runtime rather than the OS. - Goroutine vs OS thread? Goroutines are created and scheduled by Go's runtime, start with a 2 KB growable stack and are cheap to create and switch; OS threads are created by the kernel, have big fixed stacks (8 MB by default on Linux) and are more expensive. Many goroutines are multiplexed onto a few threads.
- What happens to running goroutines when main returns? The program exits; they are stopped without finishing and without deferred calls running.
- Why not use
time.Sleepto wait for goroutines? It's a guess: too short loses work, too long wastes time. Usesync.WaitGroup, channels orerrgroup. - Concurrency vs parallelism? Concurrency is structuring a program as independently executing pieces (dealing with many things); parallelism is executing them simultaneously on multiple cores (doing many things). Concurrency enables parallelism but doesn't require it.
- What does GOMAXPROCS control, and what is the default? The maximum number of CPUs executing Go code simultaneously; defaults to
runtime.NumCPU().GOMAXPROCS(0)reads it. - What does
runtime.Goscheddo? Do you need it? Yields the processor so other goroutines can run; the current one resumes later. Rarely needed because the scheduler preempts goroutines. - Will more goroutines speed up a CPU-bound task on 2 cores? Not beyond about 2 busy goroutines; extra ones only take turns.
- What is CSP, and what does "share memory by communicating" mean? Hoare's 1978 model of sequential processes cooperating by message passing; in Go, pass data between goroutines over channels so one goroutine owns it at a time, instead of many goroutines sharing variables under locks.
- Can a go statement return a value? No; results come back via channels or by writing into memory the caller waits for (with proper synchronisation).
Glossary
| Term | Meaning | Example |
|---|---|---|
| Sequential | one step after another; each starts when the previous one ends | five makeChai calls: 5 s |
| Function call (normal) | runs a function and waits until it returns | makeChai(1) |
| Blocking | waiting, unable to continue until something happens | time.Sleep, wg.Wait() |
| I/O-bound | spends its time waiting for input/output | network calls, sleeping |
| CPU-bound | spends its time computing | the count loop |
| Concurrency | dealing with many things at once: independent pieces that can each make progress | one cook, five pans |
| Parallelism | doing many things at once: pieces running at the same instant on different cores | two cooks, two stoves |
| CSP (Communicating Sequential Processes) | Hoare's 1978 model: sequential processes that cooperate by sending messages | goroutines + channels |
| Process (in CSP) | an independent worker doing one thing at a time | a goroutine |
| Goroutine | a function running independently and concurrently, managed by Go's runtime | go makeChai(1) |
go statement |
starts a function call as a goroutine and does not wait | go func() { ... }() |
| Main goroutine | the goroutine that runs main; when it returns, the program ends |
main() |
| Anonymous function / function literal | a function without a name, written inline | func() { ... }() |
time.Sleep |
pauses the current goroutine for a duration | time.Sleep(time.Second) |
time.Since |
time passed since a moment | time.Since(start) |
sync.WaitGroup |
a counter of unfinished goroutines to wait for (episode 45) | wg.Add(1), wg.Done(), wg.Wait() |
| Channel | a typed pipe goroutines send values through (episode 47) | ch <- v |
| Operating system (OS) | the program that runs the computer and shares it among programs | Linux, Windows |
| OS thread | a worker created and scheduled by the operating system | a Java Thread |
| Stack | memory where a running function keeps locals and its return place | 2 KB for a new goroutine |
| Cheap goroutine stacks | goroutines start small (2 KB since Go 1.4) and grow as needed | 100,000 goroutines ≈ 195 MB |
ulimit -s |
shell command showing the default thread stack size (in KB) | 8192 = 8 MB |
| Runtime (Go runtime) | the part of Go inside every program: scheduler, garbage collector, memory | runs your goroutines |
| Scheduler | the part of the runtime that decides which goroutine runs on which thread | episode 44 |
| Multiplexing | sharing a few resources among many users | many goroutines on a few threads |
| CPU | the chip that runs instructions | |
| Core | one processing unit of a CPU; one "pair of hands" | this machine has 2 |
runtime.NumCPU |
number of CPU cores Go can use | 2 |
runtime.GOMAXPROCS |
sets max CPUs running Go code at once, returns the old value; 0 just asks |
runtime.GOMAXPROCS(1) |
runtime.NumGoroutine |
how many goroutines exist right now | 100001 |
runtime.ReadMemStats / StackInuse |
fills memory statistics / bytes used by stacks | m.StackInuse/1024/1024 |
runtime.Gosched |
yield: let other goroutines run, then continue | runtime.Gosched() |
| Yield | voluntarily give up the CPU for a moment | "you go now" |
| Preemption | the scheduler interrupting a running goroutine to let others run | since Go 1.14 |
| Race condition | goroutines changing shared data at once, losing updates | two helpers writing 42 |
| Mutex | a lock: one goroutine at a time in a section of code (episode 45) | sync.Mutex |
| "Share memory by communicating" | pass data between goroutines over channels instead of sharing variables | Effective Go's slogan |
Summary
- A normal call waits;
go f(x)startsfas a goroutine and moves on. - When
mainreturns, the program ends; other goroutines are stopped mid-work. time.Sleepis a guess; wait for the work to be done withsync.WaitGroup(episode 45) or channels (episode 47).- Goroutines are cheap: a 2 KB starting stack (since Go 1.4) that grows; 100,000 took ~195 MB. An OS thread's stack here is 8 MB. The runtime multiplexes many goroutines onto a few threads.
- Concurrency = dealing with many things (structure); parallelism = doing many things (execution on many cores).
runtime.NumCPU,runtime.GOMAXPROCS(default = NumCPU,0= ask),runtime.NumGoroutine.- Waiting work speeds up even on one core; CPU work needs more cores.
runtime.Goschedyields; rarely needed.- CSP (Hoare, 1978): "Do not communicate by sharing memory; instead, share memory by communicating."
Next episode: The Go scheduler: the G-M-P model, run queues, work stealing, preemption, blocking system calls, the network poller, stack growth.