These are the notes for Go episode 79, the second interview-prep episode. Concurrency questions are where interviews separate people who have used goroutines from people who understand them. Each of the ten questions starts with the obvious code, which fails for real below (missing output, a deadlock, a leak, lost updates, five database connections), then we explain why, fix it, and state the rule.
All outputs below are from real runs (Go 1.24.7, linux/amd64, 2 CPUs, 14 November 2026), through the same runner the video's compiler uses. The runner prints each command as $ command and prints the error stream (stderr) after the normal output. Concurrent programs can print in a different order from run to run; where that matters, the notes say so.
Facts and sources
go help build(Go 1.24.7): "-race enable data race detection. Supported only on linux/amd64, freebsd/amd64, darwin/amd64, darwin/arm64, windows/amd64, linux/ppc64le and linux/arm64 (only for 48-bit VMA)." (On Linux the race detector also needs cgo, i.e. a C compiler.)- The Go memory model (
doc/go_mem.html): "A data race is defined as a write to a memory location happening concurrently with another read or write to that same location, unless all the accesses involved are atomic data accesses as provided by the sync/atomic package." go doc sync.Once: "Once is an object that will perform exactly one action."go doc sync.Mutex: "A Mutex is a mutual exclusion lock. The zero value for a Mutex is an unlocked mutex."go doc sync.OnceValue:func OnceValue[T any](f func() T) func() T.- The 8 MB thread stack and 2 KB goroutine stack were measured in episode 77 on this machine.
Q1 · Goroutines vs threads
A goroutine is a function running at the same time as the rest of the program, started with the go statement (episode 43).
main.go:
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
go fmt.Println("sending SMS", i) // send in the background
}
fmt.Println("main done")
}
Commands:
$ go run .
Output:
$ go run .
main done
Usually only main done (once in a while one SMS line slips out first). When main returns, the program exits, and every other goroutine is stopped mid-way without warning.
The fix is a sync.WaitGroup (episode 45), a counter of unfinished work: Add(1) before each go, Done() when each finishes, Wait() blocks until the count is 0.
main.go:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1) // one more to wait for
go func() {
defer wg.Done() // this one is finished
fmt.Println("sending SMS", i)
}()
}
wg.Wait() // block until the count is back to 0
fmt.Println("main done")
}
Commands:
$ go run .
Output:
$ go run .
sending SMS 1
sending SMS 2
sending SMS 3
main done
All three lines arrive, in whatever order the scheduler chose.
| OS thread | goroutine | |
|---|---|---|
| stack | fixed, 8 MB default here | starts at 2 KB, grows by copying (episode 77) |
| scheduled by | the operating system kernel | the Go runtime: M:N scheduling, many goroutines (G) on a few OS threads (M) through processors (P) (episode 44) |
| switch cost | a trip into the kernel | cheap, in user space |
| identity | thread ID | none visible; can't be killed from outside |
| how many | thousands | hundreds of thousands |
Rule: every goroutine needs an owner that waits for it (WaitGroup, channel, errgroup) and a way to stop.
Q2 · Buffered vs unbuffered channels
main.go:
package main
import "fmt"
func main() {
orders := make(chan string) // unbuffered: no space at all
orders <- "chai" // send... who receives?
fmt.Println(<-orders)
}
Commands:
$ go run .
Output:
$ go run .
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
main.go:7 +0x36
exit status 2
A deadlock is when goroutines wait for each other forever. An unbuffered channel (make(chan T)) is a cup passed hand to hand: a send waits until a receiver takes it. The only receiver is the next line of the same goroutine, which is never reached. goroutine 1 [chan send] says where it is stuck.
A buffered channel (make(chan T, n)) is a tray with n spots: a send waits only when it is full, a receive only when it is empty.
main.go:
package main
import "fmt"
func main() {
tray := make(chan string, 2) // buffered: room for 2
tray <- "chai"
tray <- "samosa"
fmt.Println(len(tray), cap(tray))
fmt.Println(<-tray, <-tray)
bell := make(chan string) // unbuffered: a handover
go func() { bell <- "order ready" }()
fmt.Println(<-bell) // waits until the sender arrives
}
Commands:
$ go run .
Output:
$ go run .
2 2
chai samosa
order ready
| unbuffered | buffered (cap n) | |
|---|---|---|
| send blocks | until a receiver arrives | only when n items are waiting |
| receive blocks | until a sender arrives | only when empty |
| use it for | synchronisation, handovers, signals | queues, smoothing bursts, limiting (semaphore) |
Rule: unbuffered = a synchronous handover; buffered = a fixed-size queue. A buffer doesn't fix a design that has no receiver; it only delays the deadlock (see the quiz).
Q3 · Spotting deadlocks
main.go:
package main
import "fmt"
func main() {
orders := make(chan string)
go func() {
for _, o := range []string{"chai", "vada", "poha"} {
orders <- o
}
// forgot: close(orders)
}()
for o := range orders { // keeps waiting for more
fmt.Println("cooking", o)
}
fmt.Println("kitchen closed")
}
Commands:
$ go run .
Output:
$ go run .
cooking chai
cooking vada
cooking poha
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
main.go:13 +0xe7
exit status 2
for o := range orders receives until the channel is closed. Nobody closed it, so after three orders main waits forever ([chan receive]). The sender closes when it's done:
main.go:
package main
import "fmt"
func main() {
orders := make(chan string)
go func() {
for _, o := range []string{"chai", "vada", "poha"} {
orders <- o
}
close(orders) // no more orders: range can stop
}()
for o := range orders { // keeps waiting for more
fmt.Println("cooking", o)
}
fmt.Println("kitchen closed")
}
Commands:
$ go run .
Output:
$ go run .
cooking chai
cooking vada
cooking poha
kitchen closed
Two more classic deadlocks, both real:
A WaitGroup whose count never reaches zero (one path forgets Done):
main.go:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
if i == 1 {
return // forgot wg.Done() on this path
}
wg.Done()
}()
}
wg.Wait()
fmt.Println("all done")
}
Commands:
$ go run .
Output:
$ go run .
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [sync.WaitGroup.Wait]:
sync.runtime_SemacquireWaitGroup(0xc00000e048?)
/usr/local/go1.24.7/src/runtime/sema.go:110 +0x25
sync.(*WaitGroup).Wait(0x40afe8?)
/usr/local/go1.24.7/src/sync/waitgroup.go:118 +0x48
main.main()
main.go:19 +0xb7
exit status 2
Two locks taken in opposite orders (a sale locks stock then cash; a refund locks cash then stock):
main.go:
package main
import (
"fmt"
"sync"
"time"
)
var stock, cash sync.Mutex
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() { // sale: stock, then cash
defer wg.Done()
stock.Lock()
time.Sleep(10 * time.Millisecond)
cash.Lock()
cash.Unlock()
stock.Unlock()
}()
go func() { // refund: cash, then stock
defer wg.Done()
cash.Lock()
time.Sleep(10 * time.Millisecond)
stock.Lock()
stock.Unlock()
cash.Unlock()
}()
wg.Wait()
fmt.Println("done")
}
Commands:
$ go run .
Output:
$ go run .
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [sync.WaitGroup.Wait]:
sync.runtime_SemacquireWaitGroup(0xc00008a070?)
/usr/local/go1.24.7/src/runtime/sema.go:110 +0x25
sync.(*WaitGroup).Wait(0x0?)
/usr/local/go1.24.7/src/sync/waitgroup.go:118 +0x48
main.main()
main.go:30 +0xaf
goroutine 20 [sync.Mutex.Lock]:
internal/sync.runtime_SemacquireMutex(0x0?, 0x0?, 0x0?)
/usr/local/go1.24.7/src/runtime/sema.go:95 +0x25
... (25 more lines of the trace)
| Deadlock | Trace shows | Fix |
|---|---|---|
| unbuffered send, no receiver | [chan send] |
receive in another goroutine, or buffer if a queue is intended |
| range over a never-closed channel | [chan receive] |
the sender calls close |
Add without a matching Done |
[sync.WaitGroup.Wait] |
defer wg.Done() as the first line |
| locks in opposite orders | [sync.Mutex.Lock] |
always lock in one global order, or use one lock |
The runtime only says "all goroutines are asleep" when every goroutine is stuck. In a server, other goroutines (the HTTP listener, timers) keep running, so a deadlocked part just hangs silently: use timeouts, pprof's goroutine profile (episode 57), and go test -timeout.
Rule: the sender closes, never the receiver; defer wg.Done(); one lock order.
Q4 · A worker pool, live
A worker pool is a fixed number of goroutines (workers) taking jobs from one channel, so at most N jobs run at once. Like three packers at one conveyor belt.
main.go:
package main
import (
"fmt"
"sync"
"time"
)
func pack(id int) string {
time.Sleep(100 * time.Millisecond) // packing takes time
return fmt.Sprint("order ", id, " packed")
}
func main() {
start := time.Now()
jobs := make(chan int)
results := make(chan string)
var wg sync.WaitGroup
for w := 1; w <= 3; w++ { // 3 workers
wg.Add(1)
go func() {
defer wg.Done()
for id := range jobs { // take jobs until jobs is closed
results <- pack(id)
}
}()
}
go func() {
for id := 1; id <= 9; id++ {
jobs <- id
}
close(jobs) // no more work
}()
go func() {
wg.Wait()
close(results) // all workers done
}()
n := 0
for range results {
n++
}
fmt.Println(n, "orders in", time.Since(start).Round(10*time.Millisecond))
}
Commands:
$ go run .
Output:
$ go run .
9 orders in 300ms
Nine 100 ms jobs with three workers take about 300 ms instead of 900 ms.
The four parts interviewers look for:
- a
jobschannel and a producer that sends jobs and closesjobs; - N workers that
rangeoverjobs(the loop ends whenjobsis closed and drained); - a
WaitGroupfor the workers, and one goroutine that waits and then closesresults; - the consumer ranges over
results.
Who closes what: the producer closes jobs; whoever knows all workers are finished closes results. Closing results inside a worker would panic the others (send on closed channel). For pools where any job can fail, golang.org/x/sync/errgroup with SetLimit(n) does the waiting and the first error for you.
Q5 · Ordered fan-in
Fan-in means many goroutines sending into one channel. Results arrive in finishing order, not in the order you asked:
main.go:
package main
import (
"fmt"
"sync"
"time"
)
// price asks a supplier for a price; later suppliers answer faster.
func price(i int) string {
time.Sleep(time.Duration(5-i) * 40 * time.Millisecond)
return fmt.Sprint("supplier ", i)
}
func main() {
var wg sync.WaitGroup
out := make(chan string)
for i := 1; i <= 4; i++ {
wg.Add(1)
go func() { defer wg.Done(); out <- price(i) }()
}
go func() { wg.Wait(); close(out) }()
for s := range out { // fan-in: first come, first printed
fmt.Println(s)
}
}
Commands:
$ go run .
Output:
$ go run .
supplier 4
supplier 3
supplier 2
supplier 1
The fix here: one slot per goroutine in a pre-sized slice. Each goroutine writes only its own index, so no two goroutines touch the same memory and no lock is needed; wg.Wait() makes the writes visible to main.
main.go:
package main
import (
"fmt"
"sync"
"time"
)
func price(i int) string {
time.Sleep(time.Duration(5-i) * 40 * time.Millisecond)
return fmt.Sprint("supplier ", i)
}
func main() {
var wg sync.WaitGroup
answers := make([]string, 4) // one slot per supplier
for i := 1; i <= 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
answers[i-1] = price(i) // each goroutine writes only its own slot
}()
}
wg.Wait()
for _, a := range answers { // in the order we asked
fmt.Println(a)
}
}
Commands:
$ go run .
Output:
$ go run .
supplier 1
supplier 2
supplier 3
supplier 4
The other common answer: send {index, value} through the channel and place each result by its index (see the mini project solution). Rule: carry the position with the work.
Q6 · Context cancellation and goroutine leaks
A context (context.Context, episode 51) carries a deadline and a cancel signal across function calls. context.WithTimeout returns a context that expires after a duration plus a cancel function you must call.
main.go:
package main
import (
"context"
"fmt"
"runtime"
"time"
)
// slowBank answers after 200 ms.
func slowBank() string { time.Sleep(200 * time.Millisecond); return "approved" }
func pay(ctx context.Context) (string, error) {
reply := make(chan string) // unbuffered
go func() { reply <- slowBank() }()
select {
case r := <-reply:
return r, nil
case <-ctx.Done(): // the customer stopped waiting
return "", ctx.Err()
}
}
func main() {
for i := 0; i < 20; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
_, err := pay(ctx)
cancel()
if i == 0 {
fmt.Println("error:", err)
}
}
time.Sleep(300 * time.Millisecond) // every bank call has answered by now
fmt.Println("goroutines still alive:", runtime.NumGoroutine())
}
Commands:
$ go run .
Output:
$ go run .
error: context deadline exceeded
goroutines still alive: 21
The timeout works (context deadline exceeded), but 21 goroutines are still alive after every bank call has finished: each bank goroutine is stuck forever sending its late reply on an unbuffered channel that nobody reads any more. A goroutine leak is a goroutine that never ends; leaks pile up memory and eventually take a server down.
The one-character fix: a buffer of 1, so the late reply is dropped into the buffer and the goroutine ends (the channel is then garbage collected).
main.go:
package main
import (
"context"
"fmt"
"runtime"
"time"
)
// slowBank answers after 200 ms.
func slowBank() string { time.Sleep(200 * time.Millisecond); return "approved" }
func pay(ctx context.Context) (string, error) {
reply := make(chan string, 1) // room for the late answer
go func() { reply <- slowBank() }()
select {
case r := <-reply:
return r, nil
case <-ctx.Done(): // the customer stopped waiting
return "", ctx.Err()
}
}
func main() {
for i := 0; i < 20; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
_, err := pay(ctx)
cancel()
if i == 0 {
fmt.Println("error:", err)
}
}
time.Sleep(300 * time.Millisecond) // every bank call has answered by now
fmt.Println("goroutines still alive:", runtime.NumGoroutine())
}
Commands:
$ go run .
Output:
$ go run .
error: context deadline exceeded
goroutines still alive: 1
Better still, pass the context into the slow work so it stops early (mini project 3):
main.go:
package main
import (
"context"
"fmt"
"runtime"
"time"
)
// slowBank now listens to the context itself and stops early.
func slowBank(ctx context.Context) (string, error) {
select {
case <-time.After(200 * time.Millisecond):
return "approved", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
for i := 0; i < 20; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
_, err := slowBank(ctx)
cancel()
if i == 0 {
fmt.Println("error:", err)
}
}
fmt.Println("goroutines still alive:", runtime.NumGoroutine())
}
Commands:
$ go run .
Output:
$ go run .
error: context deadline exceeded
goroutines still alive: 1
Rules: call cancel() (usually defer cancel()) for every WithTimeout/WithCancel; every goroutine you start must be able to finish even when nobody wants its result; check leaks with runtime.NumGoroutine() in tests or go.uber.org/goleak.
Q7 · Data races and the race detector
likes++ is three steps: read, add 1, write back. Two goroutines can both read 41 and both write 42, losing one like (two cashiers, one notebook).
main.go:
package main
import (
"fmt"
"sync"
)
var likes int
func main() {
var wg sync.WaitGroup
start := make(chan struct{}) // everyone starts together
for i := 0; i < 10; i++ { // 10 phones, 100,000 likes each
wg.Add(1)
go func() {
defer wg.Done()
<-start
for j := 0; j < 100_000; j++ {
likes++ // read, add 1, write back
}
}()
}
close(start)
wg.Wait()
fmt.Println("likes:", likes, "(expected 1000000)")
}
Commands:
$ go run .
Output:
$ go run .
likes: 727254 (expected 1000000)
Fewer than a million, and a different number every run. That's a data race: a write to memory at the same time as another read or write of the same place, unless all are atomic (the Go memory model's definition).
Races often give the right answer, which is why you need a tool:
main.go:
package main
import (
"fmt"
"sync"
)
var likes int
func main() {
var wg sync.WaitGroup
for i := 0; i < 2; i++ { // just 2 phones, 1 like each
wg.Add(1)
go func() {
defer wg.Done()
likes++
}()
}
wg.Wait()
fmt.Println("likes:", likes)
}
Commands:
$ go run -race .
Output:
$ go run -race .
likes: 2
==================
WARNING: DATA RACE
Read at 0x0000006006d0 by goroutine 8:
main.main.func1()
main.go:16 +0x78
Previous write at 0x0000006006d0 by goroutine 7:
main.main.func1()
main.go:16 +0x90
Goroutine 8 (running) created at:
main.main()
main.go:14 +0x56
Goroutine 7 (finished) created at:
main.main()
main.go:14 +0x56
==================
Found 1 data race(s)
exit status 66
The answer is right (2) and the race detector still reports it: it records which memory accesses are ordered by synchronisation (locks, channels, WaitGroup) and flags two accesses that are not, whether or not a wrong value appeared. The program exits with status 66. It slows programs down several times and uses more memory, so use it in tests and CI: go test -race ./....
likes.go:
package shop
import "sync"
type Likes struct {
mu sync.Mutex
n int
}
func (l *Likes) Add() {
l.mu.Lock()
defer l.mu.Unlock()
l.n++
}
func (l *Likes) Count() int {
l.mu.Lock()
defer l.mu.Unlock()
return l.n
}
likes_test.go:
package shop
import (
"sync"
"testing"
)
func TestLikesConcurrent(t *testing.T) {
var l Likes
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Add(1)
go func() { defer wg.Done(); l.Add() }()
}
wg.Wait()
if got := l.Count(); got != 50 {
t.Fatalf("got %d likes, want 50", got)
}
}
Commands:
$ go test -race .
Output:
$ go test -race .
ok shop 1.017s
Q8 · Mutex vs channels
main.go:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var wg sync.WaitGroup
var mu sync.Mutex
likes := 0 // fix 1: a Mutex guards it
var fast atomic.Int64 // fix 2: one atomic add
start := make(chan struct{})
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
for j := 0; j < 100_000; j++ {
mu.Lock()
likes++ // only one goroutine at a time is here
mu.Unlock()
fast.Add(1)
}
}()
}
close(start)
wg.Wait()
fmt.Println("mutex:", likes, " atomic:", fast.Load())
}
Commands:
$ go run -race .
Output:
$ go run -race .
mutex: 1000000 atomic: 1000000
sync.Mutex, a mutual exclusion lock:Locklets one goroutine at a time into the critical section (the code betweenLockandUnlock).sync/atomic:atomic.Int64.Addis one indivisible CPU instruction; best for a single counter or flag.- Channel: hand the data to one owner goroutine; whoever has the value owns it.
| Use | When |
|---|---|
Mutex (or RWMutex for read-heavy) |
many goroutines share state: a cache, a map, a struct with invariants; keep the locked section short |
| atomic | one number or flag, very hot paths |
| channel | handing work or ownership between goroutines: pipelines, worker pools, signals, timeouts with select |
Rule: both are correct tools; pick the one that makes the code simplest to read and prove correct. Don't hold a lock while sending on a channel or doing I/O.
Q9 · sync.Once singletons
A singleton is one shared object for the whole program, here one database connection, created lazily (on first use).
main.go:
package main
import (
"fmt"
"sync"
"time"
)
type DB struct{ name string }
var db *DB
func connect() *DB {
fmt.Println("connecting to the database...")
time.Sleep(50 * time.Millisecond) // a slow handshake
return &DB{name: "shop"}
}
func GetDB() *DB {
if db == nil { // "only the first caller connects"
db = connect()
}
return db
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ { // 5 requests arrive together
wg.Add(1)
go func() { defer wg.Done(); GetDB() }()
}
wg.Wait()
}
Commands:
$ go run .
Output:
$ go run .
connecting to the database...
connecting to the database...
connecting to the database...
connecting to the database...
connecting to the database...
Five connections: all five goroutines checked db == nil before anyone set it. Check-then-act (test a condition, then act on it) without synchronisation is a race.
main.go:
package main
import (
"fmt"
"sync"
"time"
)
type DB struct{ name string }
var (
db *DB
once sync.Once
)
func connect() *DB {
fmt.Println("connecting to the database...")
time.Sleep(50 * time.Millisecond)
return &DB{name: "shop"}
}
func GetDB() *DB {
once.Do(func() { db = connect() }) // runs exactly once; others wait
return db
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() { defer wg.Done(); fmt.Println(GetDB().name) }()
}
wg.Wait()
}
Commands:
$ go run -race .
Output:
$ go run -race .
connecting to the database...
shop
shop
shop
shop
shop
once.Do(f) runs f exactly once; other callers block until it has returned, so they all see the connected db (the return from f "synchronizes before" the return of every Do). Go 1.21 added sync.OnceValue and sync.OnceValues, which return the value (and an error) directly:
main.go:
package main
import (
"fmt"
"sync"
)
var getConfig = sync.OnceValue(func() map[string]string {
fmt.Println("reading config...")
return map[string]string{"shop": "Raju's"}
})
func main() {
var wg sync.WaitGroup
for i := 0; i < 3; i++ {
wg.Add(1)
go func() { defer wg.Done(); fmt.Println(getConfig()["shop"]) }()
}
wg.Wait()
}
Commands:
$ go run -race .
Output:
$ go run -race .
reading config...
Raju's
Raju's
Raju's
Rule: lazy shared setup → sync.Once / sync.OnceValue. If f panics, Do considers it done; with OnceValue every caller gets the same panic.
Q10 · Printing odd and even numbers alternately
Two goroutines, one printing odd numbers and one even, must print 1 to 10 in order.
main.go:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() { // odd numbers
defer wg.Done()
for i := 1; i <= 9; i += 2 {
fmt.Print(i, " ")
}
}()
go func() { // even numbers
defer wg.Done()
for i := 2; i <= 10; i += 2 {
fmt.Print(i, " ")
}
}()
wg.Wait()
fmt.Println()
}
Commands:
$ go run .
Output:
$ go run .
2 4 6 8 10 1 3 5 7 9
In this run the even goroutine printed all its numbers first; another run could differ. Nothing makes them take turns.
main.go:
package main
import (
"fmt"
"sync"
)
func main() {
oddTurn := make(chan struct{}) // "your turn, odd"
evenTurn := make(chan struct{}) // "your turn, even"
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
for i := 1; i <= 9; i += 2 {
<-oddTurn // wait for my turn
fmt.Print(i, " ")
evenTurn <- struct{}{} // pass the turn
}
}()
go func() {
defer wg.Done()
for i := 2; i <= 10; i += 2 {
<-evenTurn
fmt.Print(i, " ")
if i < 10 {
oddTurn <- struct{}{}
}
}
}()
oddTurn <- struct{}{} // odd starts
wg.Wait()
fmt.Println()
}
Commands:
$ go run .
Output:
$ go run .
1 2 3 4 5 6 7 8 9 10
Two unbuffered channels act like a relay baton: a goroutine prints only after receiving its turn, then passes the turn on. struct{}{} (an empty struct) carries no data, only the signal. if i < 10 stops even from passing a turn after 10, which nobody would receive: a deadlock. The same idea scales to N goroutines (mini project 4).
The cheat sheet
| # | Question | Rule |
|---|---|---|
| 1 | goroutines vs threads | main returning ends everything; wait with a WaitGroup |
| 2 | buffered vs unbuffered | unbuffered = handover (sync); buffered = fixed-size queue |
| 3 | deadlocks | no receiver, no close, missing Done, lock order |
| 4 | worker pool | jobs chan, N workers, WaitGroup, close results after Wait |
| 5 | fan-in order | carry the index |
| 6 | context | always cancel(); every goroutine must be able to finish |
| 7 | races | x++ is read-add-write; test with -race |
| 8 | Mutex vs channels | Mutex/atomic for shared state, channels to hand over |
| 9 | singletons | check-then-act races: sync.Once, sync.OnceValue |
| 10 | turn-taking | channels as a baton |
Mini project: a concurrency drill
- Make the worker count a flag; time 1, 3 and 9 workers.
- Keep results in order by sending
{index, value}. - Pass the context into the slow bank call so it stops early.
- Extend the printer to three goroutines taking turns (1 2 3 4 5 6 ...).
- Run every exercise with
-race.
Solutions 1 and 2: pool with a flag and ordered results
main.go:
package main
import (
"flag"
"fmt"
"sync"
"time"
)
type result struct {
index int
text string
}
func pack(id int) string {
time.Sleep(100 * time.Millisecond)
return fmt.Sprint("order ", id, " packed")
}
func main() {
workers := flag.Int("workers", 3, "number of packers")
flag.Parse()
start := time.Now()
jobs := make(chan int)
results := make(chan result)
var wg sync.WaitGroup
for w := 0; w < *workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for id := range jobs {
results <- result{id, pack(id)} // carry the index
}
}()
}
go func() {
for id := 0; id < 9; id++ {
jobs <- id
}
close(jobs)
}()
go func() { wg.Wait(); close(results) }()
ordered := make([]string, 9)
for r := range results {
ordered[r.index] = r.text // rebuild the order
}
fmt.Println(*workers, "workers:", time.Since(start).Round(10*time.Millisecond), "first:", ordered[0], "last:", ordered[8])
}
Commands:
$ go run . -workers=1
$ go run . -workers=3
$ go run . -workers=9
Output:
$ go run . -workers=1
1 workers: 930ms first: order 0 packed last: order 8 packed
$ go run . -workers=3
3 workers: 300ms first: order 0 packed last: order 8 packed
$ go run . -workers=9
9 workers: 100ms first: order 0 packed last: order 8 packed
900 ms with 1 worker, 300 ms with 3, 100 ms with 9: the jobs are pure waiting, so more workers help until there is one per job. For CPU-bound jobs, more workers than CPUs (here 2) don't help.
Solution 3: the context inside the slow call
main.go:
package main
import (
"context"
"fmt"
"runtime"
"time"
)
// slowBank now listens to the context itself and stops early.
func slowBank(ctx context.Context) (string, error) {
select {
case <-time.After(200 * time.Millisecond):
return "approved", nil
case <-ctx.Done():
return "", ctx.Err()
}
}
func main() {
for i := 0; i < 20; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
_, err := slowBank(ctx)
cancel()
if i == 0 {
fmt.Println("error:", err)
}
}
fmt.Println("goroutines still alive:", runtime.NumGoroutine())
}
Commands:
$ go run .
The output is in Q6: one goroutine left, and slowBank returns as soon as the context expires.
Solution 4: three printers
main.go:
package main
import (
"fmt"
"sync"
)
func main() {
const n, upTo = 3, 12
turns := make([]chan struct{}, n)
for i := range turns {
turns[i] = make(chan struct{})
}
var wg sync.WaitGroup
for g := 0; g < n; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for v := g + 1; v <= upTo; v += n {
<-turns[g]
fmt.Print(v, " ")
if v < upTo {
turns[(g+1)%n] <- struct{}{} // pass the baton on
}
}
}()
}
turns[0] <- struct{}{}
wg.Wait()
fmt.Println()
}
Commands:
$ go run .
Output:
$ go run .
1 2 3 4 5 6 7 8 9 10 11 12
Common mistakes (and the real messages)
| Mistake | Real message / symptom | Why | Fix |
|---|---|---|---|
main returns before goroutines finish |
missing output, no error | program exit stops all goroutines | sync.WaitGroup |
| send on an unbuffered channel with no receiver | fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan send] |
a handover needs two goroutines | receive elsewhere |
| range over a channel nobody closes | deadlock! [chan receive] |
range waits for close | sender calls close |
a path that skips wg.Done() |
deadlock! [sync.WaitGroup.Wait] |
the count never reaches 0 | defer wg.Done() first |
| two locks in opposite orders | deadlock! [sync.Mutex.Lock] |
each holds what the other needs | one lock order |
| late reply on an unbuffered channel after a timeout | goroutines still alive: 21 |
the sender waits forever | buffer of 1, or select on ctx.Done() |
likes++ from many goroutines |
wrong totals; WARNING: DATA RACE, exit status 66 |
read-add-write isn't atomic | Mutex or atomic |
if db == nil { db = connect() } |
connecting to the database... ×5 |
check-then-act race | sync.Once |
| closing a channel from the receiver or twice | panic: send on closed channel / close of closed channel |
only the sender knows when it's done | close once, from the sender side |
Practice
- What does
go run -racecost, and why not use it in production? - Can you receive from a closed channel? What do you get?
ch := make(chan int); close(ch); ch <- 1— what happens?- Why must
wg.Add(1)be called beforego, not inside the goroutine? - How would you limit a program to at most 5 concurrent HTTP requests without a worker pool?
- Name two ways to stop a goroutine that is looping forever.
Solutions
1. Programs run several times slower and use more memory, because every memory access is tracked. Use it in tests, CI and staging; it only finds races on code paths that actually run.
2. Yes: buffered values first, then the zero value immediately with ok == false (v, ok := <-ch).
3. panic: send on closed channel.
4. If Add runs inside the goroutine, Wait may run first, see a count of 0 and return before the goroutine even started.
5. A buffered channel as a semaphore: sem := make(chan struct{}, 5); before each request sem <- struct{}{}, after it <-sem. Or errgroup.Group.SetLimit(5).
6. Cancel a context it checks in a select (case <-ctx.Done(): return), or close a done channel it selects on. There is no way to kill a goroutine from outside.
Quick quiz
func main() {
ch := make(chan int, 1)
ch <- 1
ch <- 2
fmt.Println(<-ch, <-ch)
}
- A.
1 2 - B.
2 1 - C. deadlock
- D. prints 1, then panics
Answer
C.
Output:
$ go run .
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
main.go:8 +0x47
exit status 2
The buffer holds one value. The second send finds it full and waits for a receiver, but the only receiver is main itself, further down.
Interview questions (with model answers)
- Goroutine vs thread? Goroutines are managed by the Go runtime, start with 2 KB growable stacks, and are multiplexed M:N onto OS threads; switching is cheap. Threads are kernel-scheduled with fixed MB-sized stacks.
- Buffered vs unbuffered channel? Unbuffered: send and receive meet (synchronisation). Buffered: a queue of fixed capacity; send blocks only when full.
- What causes "all goroutines are asleep - deadlock!"? Every goroutine is blocked: a send/receive with no partner, a range over an unclosed channel, a WaitGroup that never reaches 0, or a lock cycle.
- Code a worker pool. (Q4.) Mention who closes
jobsandresults, anderrgroup.SetLimitas the library answer. - How do you keep results in order? Index slots, or send the index with the result.
- What is a goroutine leak and how do you prevent it? A goroutine blocked forever. Always give goroutines an exit: buffered result channels,
selectonctx.Done(), closing channels, and test with goroutine counts. - What is a data race and how do you find it? Concurrent access to the same memory with at least one write and no synchronisation;
go test -race. - Mutex or channel? Mutex for protecting shared state; channels for transferring ownership and coordinating; atomic for single counters.
- How do you implement a thread-safe singleton?
sync.Onceorsync.OnceValue; never check-then-act. - Print odd and even numbers alternately with two goroutines. (Q10.) Two unbuffered turn channels; the last goroutine doesn't pass the turn after the final number.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Concurrency | structuring a program as tasks that can make progress independently | three SMS senders |
| Goroutine | a function running concurrently, managed by the Go runtime | go send(i) |
| OS thread | the kernel's unit of execution | 8 MB stack here |
| Scheduler (M:N) | the runtime part that runs many goroutines (G) on a few threads (M) through processors (P) | episode 44 |
sync.WaitGroup |
a counter to wait for goroutines: Add, Done, Wait | wg.Wait() |
| Channel | a typed pipe between goroutines | make(chan string) |
| Unbuffered channel | capacity 0: send waits for a receiver | bell |
| Buffered channel | capacity n: a queue | make(chan string, 2) |
| Deadlock | goroutines waiting for each other forever | all goroutines are asleep |
close |
marks a channel as done; range then stops |
close(orders) |
| Worker pool | N goroutines taking jobs from one channel | 3 packers |
| Producer / consumer | the code that sends jobs / receives results | the feeder goroutine / main |
| Fan-out / fan-in | spreading work to many goroutines / merging their results into one channel | the price lookups |
context.Context |
carries a deadline and cancel signal | ctx.Done() |
context.WithTimeout |
a context that expires after a duration, plus cancel |
50 ms |
select |
waits on several channel operations, runs the first ready one | reply or timeout |
| Goroutine leak | a goroutine that never finishes | 21 alive |
| Data race | concurrent access to the same memory, at least one write, not synchronised | likes++ |
| Race detector | -race: a tool that reports data races at run time |
WARNING: DATA RACE |
| Atomic operation | an indivisible read-modify-write | fast.Add(1) |
sync.Mutex |
a mutual exclusion lock | mu.Lock() |
| Critical section | the code between Lock and Unlock |
likes++ |
sync.RWMutex |
many readers or one writer | read-heavy caches |
| Singleton | one shared instance for the whole program | the DB connection |
| Check-then-act | testing a condition and acting on it as two steps; racy without a lock | if db == nil |
sync.Once |
performs exactly one action | once.Do(connect) |
sync.OnceValue |
Once that returns a value (Go 1.21) |
getConfig() |
struct{} |
the empty struct: zero bytes, used as a pure signal | chan struct{} |
| Semaphore | a counter limiting how many run at once; a buffered channel works as one | make(chan struct{}, 5) |
errgroup |
golang.org/x/sync/errgroup: wait for goroutines, keep the first error, limit concurrency |
g.SetLimit(3) |
Summary
mainreturning ends the program: wait for goroutines.- Unbuffered channels synchronise; buffered channels queue.
- Know the four deadlocks and read the
[chan send]/[chan receive]/[sync...]labels. - A worker pool = jobs channel + N workers + WaitGroup + closing results after Wait.
- Fan-in loses order: carry the index.
- Cancel contexts and give every goroutine a way out, or it leaks.
x++is not atomic:-racefinds races even when the answer looks right.- Mutex/atomic for shared state, channels for handing over.
sync.Oncefor lazy singletons.- Channels as a baton make goroutines take turns.
Next episode: Interview prep: backend and system design in Go.