Races, deadlocks and leaks
Most concurrency bugs have a small number of shapes. Here is each shape as a real program, with what each tool reports, and the fix. No tool finds all of them.
- 1Each tool finds one class: -race finds data races, the runtime finds full deadlocks, vet finds copied locks, the leak profile finds unreachable waits.
- 2A clean -race run proves no data race ran. It says nothing about the logic.
- 3Read a stack dump from the bracket: it says what each goroutine waits for.
- 4The runtime reports a deadlock only when every goroutine is asleep. In a server that never happens.
func (a *account) get() int {
a.mu.Lock()
defer a.mu.Unlock()
return a.balance
}
func (a *account) sub(n int) {
a.mu.Lock()
defer a.mu.Unlock()
a.balance -= n
}
func (a *account) withdrawLocked(n int) {
if a.get() >= n {1
time.Sleep(20 * time.Millisecond)
a.sub(n)2
}
}- 1The lock ends before this comparison. Another goroutine can act now.
- 2This write trusts a balance that is already old.
| form | 2 withdrawals of 100 from 100 | -race |
|---|---|---|
| No lock | balance: -100 | Exit 66, found |
| A lock per step | balance: -100 | Exit 0, silent |
| One lock over both | balance: 0 | Correct |
func (a *account) withdraw(n int) bool {
a.mu.Lock()
defer a.mu.Unlock()
if a.balance < n {1
return false
}
a.balance -= n
return true
}- 1The check and the write are inside one critical section.
Each step is locked, so the race detector is silent. The check and the act are still two steps. I lock over both.
| hazard | -race | runtime stops it | go vet | goroutineleak | fix |
|---|---|---|---|---|---|
| Concurrent map writes | Reports | concurrent map writes | Silent | 0 found | Mutex around the map |
| Check-then-act, no lock | Reports | Runs on | Silent | 0 found | One lock over both steps |
| Check-then-act, a lock per step | Silent | Runs on | Silent | 0 found | One lock over both steps |
| Slice append | Reports | Runs on | Silent | 0 found | Preallocate, write by index |
| A captured variable | Reports | Runs on | Silent | 0 found | One slot per goroutine |
| Pointer published before it is ready | Reports | Runs on | Silent | 0 found | Build, then an atomic store |
| Lock order | Silent | deadlock | Silent | 0 found | One global order |
| Send with no receiver | Silent | deadlock | Silent | 0 found | Buffer, or select on ctx.Done |
| A goroutine locks its own mutex twice | Silent | deadlock | Silent | 0 found | A helper that assumes the lock |
| WaitGroup miscount | Silent | deadlock | Silent | 0 found | wg.Go |
| Mutex copied by value | Silent | deadlock | Reports | 0 found | Pointer receiver |
| Deadlock with another goroutine alive | Silent | Runs on | Silent | 1 found | Find it with the leak profile |
| Leak: an unreachable channel | Silent | Runs on | Silent | 3 found | Buffer, or select on ctx.Done |
| Leak: a global channel | Silent | Runs on | Silent | 0 found | Do not share a channel in a global |
The leak column has no meaning for a program that crashes first. It shows what each program reports. A race needs the racing code to run, and the map crash is best effort.
I match the bug to the tool. The race detector for memory, vet for copies, the leak profile for stuck goroutines, and a counting test for logic.
func bug() int {
m := map[int]int{}
var wg sync.WaitGroup
for g := range 2 {
wg.Go(func() {
time.Sleep(time.Duration(g) * 10 * time.Millisecond)
m[g] = g1
})
}
wg.Wait()
return len(m)
}- 1One write, then another, with no edge. A sleep orders them in time only.
==================
WARNING: DATA RACE
Write at 0x00c0001a20f0 by goroutine 8:
runtime.mapassign_fast64()1
$GOROOT/src/internal/runtime/maps/runtime_fast64.go:182 +0x0
main.bug.func1()
main.go:19 +0x50
Previous write at 0x00c0001a20f0 by goroutine 7:
runtime.mapassign_fast64()
$GOROOT/src/internal/runtime/maps/runtime_fast64.go:182 +0x0
main.bug.func1()
main.go:19 +0x50
Goroutine 8 (running) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
main.main()
main.go:55 +0x22c
Goroutine 7 (finished) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
main.main()
main.go:55 +0x22c
==================- 1The access is inside the runtime. The next frame is your code.
type store struct {
mu sync.Mutex1
m map[int]int
}
func (s *store) set(k, v int) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[k] = v
}
func fix() int {
s := store{m: map[int]int{}}
var wg sync.WaitGroup
for g := range 2 {
wg.Go(func() { s.set(g, g) })
}
wg.Wait()
return len(s.m)
}- 1Put the lock beside what it guards, as the first field.
Unguarded map writes can crash the process, and recover cannot stop that. I put a mutex beside the map on line one.
func bug() int {
var out []int
var wg sync.WaitGroup
for i := range n {
wg.Go(func() { out = append(out, i)1 })
}
wg.Wait()
return len(out)
}- 1A read of the header, a store, and a write of the header. Two goroutines can use one slot.
==================
WARNING: DATA RACE
Write at 0x00c000014018 by goroutine 7:
main.bug.func1()
main.go:17 +0xac
Previous read at 0x00c000014018 by goroutine 8:
main.bug.func1()
main.go:17 +0x37
Goroutine 7 (running) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
main.main()
main.go:41 +0x22c
Goroutine 8 (running) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
main.main()
main.go:41 +0x22c
==================func fix() int {
out := make([]int, n)
var wg sync.WaitGroup
for i := range n {
wg.Go(func() { out[i] = i1 })
}
wg.Wait()
return len(out)
}- 1Each element is a separate memory location, so no lock is needed.
Append reads and writes the slice header, so two appends lose items. I preallocate and give each goroutine one index.
func bug() error {
var err error
var wg sync.WaitGroup
wg.Go(func() { err = save() })
wg.Go(func() { err = index()1 })
wg.Wait()
return err
}- 1The later nil replaces the failure.
==================
WARNING: DATA RACE
Write at 0x00c0001a4010 by goroutine 8:
main.bug.func2()
main.go:27 +0x38
Previous write at 0x00c0001a4010 by goroutine 7:
main.bug.func1()
main.go:26 +0x52
Goroutine 8 (running) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
main.main()
main.go:49 +0x244
Goroutine 7 (finished) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
main.main()
main.go:49 +0x244
==================func fix() error {
errs := make([]error, 2)
var wg sync.WaitGroup
wg.Go(func() { errs[0] = save() })
wg.Go(func() { errs[1] = index() })
wg.Wait()
return errors.Join(errs...)1
}- 1Each goroutine owns one slot. This prints the disk error.
Closures share the variable they capture. Since Go 1.22 the loop variable is safe, but a shared err is not.
var current *server
func bug() int {
go func() {
s := new(server)
current = s1
time.Sleep(10 * time.Millisecond)
s.port = 8080
}()
time.Sleep(5 * time.Millisecond)
port := current.port
time.Sleep(10 * time.Millisecond)
return port
}- 1The pointer goes public while the struct is empty.
==================
WARNING: DATA RACE
Read at 0x000002499880 by main goroutine:
main.bug()
main.go:25 +0x3a
main.main()
main.go:54 +0x22c
Previous write at 0x000002499880 by goroutine 7:
main.bug.func1()
main.go:20 +0x38
Goroutine 7 (running) created at:
main.bug()
main.go:18 +0x24
main.main()
main.go:54 +0x22c
==================var ready atomic.Pointer[server]
func fix() int {
go func() {
s := new(server)
s.port = 8080
ready.Store(s)1
}()
for {
if s := ready.Load(); s != nil {
return s.port
}
time.Sleep(time.Millisecond)
}
}- 1The write to port comes before this store. See G9 for the edge.
I build the whole value, then publish one pointer with an atomic store. After that, no goroutine writes to it.
| shape | cause | recorded output | status |
|---|---|---|---|
| Lock order | Two goroutines take two locks in opposite orders. | fatal error: all goroutines are asleep - deadlock! goroutine 1 [sync.WaitGroup.Wait]: | Exit 2 |
| Send, no receiver | An unbuffered send with no other goroutine. | fatal error: all goroutines are asleep - deadlock! goroutine 1 [chan send]: | Exit 2 |
| WaitGroup count too high | Add(2) with one Done. Wait never returns. | fatal error: all goroutines are asleep - deadlock! goroutine 1 [sync.WaitGroup.Wait]: | Exit 2 |
| Relock | A Go mutex is not reentrant. incr holds it and calls get. | fatal error: all goroutines are asleep - deadlock! goroutine 1 [sync.Mutex.Lock]: | Exit 2 |
| Copied mutex | A value receiver copies a locked mutex. | fatal error: all goroutines are asleep - deadlock! goroutine 1 [sync.Mutex.Lock]: | Exit 2 |
| Any of these, plus one live goroutine | A timer or a server keeps one goroutine awake. | 200 ms later: no deadlock report leaked: 1 | No report from the runtime |
All the goroutines are asleep is the easy case. The bracket after each goroutine number says what it waits for.
// Two transfers take the same two locks in opposite orders. The labels name
// each goroutine; since Go 1.27 a stack dump prints them.
package main
import (
"context"
"runtime/pprof"
"sync"
"time"
)
type account struct {
mu sync.Mutex
balance int
}
func transfer(from, to *account, n int) {
from.mu.Lock()1
defer from.mu.Unlock()
time.Sleep(10 * time.Millisecond)
to.mu.Lock()2
defer to.mu.Unlock()
from.balance -= n
to.balance += n
}
func main() {
a, b := new(account), new(account)
var wg sync.WaitGroup
wg.Go(func() {
labels := pprof.Labels("transfer", "a-to-b")3
pprof.Do(context.Background(), labels, func(context.Context) {
transfer(a, b, 10)
})
})
wg.Go(func() {
labels := pprof.Labels("transfer", "b-to-a")
pprof.Do(context.Background(), labels, func(context.Context) {
transfer(b, a, 20)
})
})
wg.Wait()
}- 1First lock. Both goroutines get one.
- 2Second lock. Each one waits for the other.
- 3Since Go 1.27, these labels appear in the header of a stack dump.
fatal error: all goroutines are asleep1 - deadlock!
goroutine 1 [sync.WaitGroup.Wait]2:
sync.runtime_SemacquireWaitGroup(0x4ef8b38?, 0x78?)
$GOROOT/src/runtime/sema.go:114 +0x2e
sync.(*WaitGroup).Wait(0x36fd3b510040)
$GOROOT/src/sync/waitgroup.go:206 +0x85
main.main()
main.go:42 +0x139
goroutine 19 [sync.Mutex.Lock] {transfer: "a-to-b"}3:
internal/sync.runtime_SemacquireMutex4(0x20?, 0x8?, 0x36fd3b47c000?)
$GOROOT/src/runtime/sema.go:95 +0x25
internal/sync.(*Mutex).lockSlow(0x36fd3b510030)
$GOROOT/src/internal/sync/mutex.go:149 +0x15a
internal/sync.(*Mutex).Lock(...)
$GOROOT/src/internal/sync/mutex.go:70
sync.(*Mutex).Lock(...)
$GOROOT/src/sync/mutex.go:46
main.transfer(50x36fd3b510020, 0x36fd3b510030, 0xa)
main.go:21 +0x9c
main.main.func1.1({0x4f02640?, 0x36fd3b47c000?})
main.go:33 +0x25
runtime/pprof.Do({0x4f02608?, 0x4f2cd80?}, {{0x36fd3b470020?, 0x0?, 0x0?}}, 0x36fd3b453768)
$GOROOT/src/runtime/pprof/runtime.go:57 +0x8c
main.main.func1()
main.go:32 +0xa5
sync.(*WaitGroup).Go.func1()
$GOROOT/src/sync/waitgroup.go:258 +0x4a
created by sync.(*WaitGroup).Go in goroutine 16
$GOROOT/src/sync/waitgroup.go:238 +0x7d
goroutine 20 [sync.Mutex.Lock] {transfer: "b-to-a"}:
internal/sync.runtime_SemacquireMutex(0x3c?, 0xc8?, 0x36fd3b5141e0?)
$GOROOT/src/runtime/sema.go:95 +0x25
internal/sync.(*Mutex).lockSlow(0x36fd3b510020)
$GOROOT/src/internal/sync/mutex.go:149 +0x15a
internal/sync.(*Mutex).Lock(...)
$GOROOT/src/internal/sync/mutex.go:70
sync.(*Mutex).Lock(...)
$GOROOT/src/sync/mutex.go:46
main.transfer(0x36fd3b510030, 0x36fd3b510020, 0x14)
main.go:21 +0x9c
main.main.func2.1({0x4f02640?, 0x36fd3b5141e0?})
main.go:39 +0x25
runtime/pprof.Do({0x4f02608?, 0x4f2cd80?}, {{0x36fd3b522080?, 0x0?, 0x0?}}, 0x36fd3b453f68)
$GOROOT/src/runtime/pprof/runtime.go:57 +0x8c
main.main.func2()
main.go:38 +0xa5
sync.(*WaitGroup).Go.func1()
$GOROOT/src/sync/waitgroup.go:258 +0x4a
created by sync.(*WaitGroup).Go in goroutine 1
$GOROOT/src/sync/waitgroup.go:238 +0x7d- 1Every goroutine is blocked, and no timer or network wait can wake one.
- 2The bracket says what this goroutine waits for. Main is only waiting for the others.
- 3The goroutine label. It names the work without a look at the arguments.
- 4Skip the frames in sync and runtime. They only say how it parks.
- 5The first frame of your own code. The line number is the second Lock.
- 6Where this goroutine began. Follow it when a helper starts many goroutines.
I read the brackets first, then the first frame in my own package. Two goroutines on one mutex type, in opposite argument order, is a lock cycle.
// Account has a lock and a balance.
type Account struct {
ID int
mu sync.Mutex
Balance int
}
// Transfer moves n between accounts. It always locks the lower ID first, so
// two opposite transfers take the locks in one global order.
func Transfer(from, to *Account, n int) error {
if from.ID == to.ID2 {
return errors.New("transfer to the same account")
}
first, second := from, to
if second.ID < first.ID {1
first, second = second, first
}
first.mu.Lock()
defer first.mu.Unlock()
second.mu.Lock()
defer second.mu.Unlock()
if from.Balance < n {
return errors.New("insufficient funds")
}
from.Balance -= n
to.Balance += n
return nil
}- 1Sort by a stable key, here the ID. Two opposite transfers now lock in one order.
- 2A transfer to itself would lock one mutex twice.
I rank every lock and always take the lower rank first. A cycle then cannot form, whatever the callers do.
main.go:14:16: byValue passes lock by value: guarded
contains sync.Mutex
main.go:16:9: receiver passes lock by value: guarded
contains sync.Mutex
main.go:18:44: return copies lock value: guarded
contains sync.Mutex
main.go:21:7: assignment copies lock value to h: guarded
contains sync.Mutex
main.go:26:9: range var g copies lock: guarded
contains sync.Mutex
main.go:31:19: waitgroup passes lock by value: sync.WaitGroup
contains sync.noCopy
main.go:33:19: atomicCopy passes lock by value: sync/atomic.Int64
contains sync/atomic.noCopy
main.go:37:10: call of byValue copies lock value: guarded
contains sync.Mutex| copied by | vet |
|---|---|
| Parameter, receiver or return value | Reports |
| Assignment or range variable | Reports |
| WaitGroup and atomic types | Reports |
Each type here carries a noCopy marker or a lock. Add a sync.Mutex to your struct, and vet protects it too.
Vet catches a copied lock before the code runs. A struct with a mutex always goes by pointer.
// The first bad item returns early, and the other workers block on send.
package main
import (
"errors"
"fmt"
"io"
"os"
"runtime"
"runtime/pprof"
"time"
)
func process(items []int) error {
ch := make(chan error)1
for _, it := range items {
go func() {
if it < 0 {
ch <- errors.New("bad item")
return
}
ch <- nil
}()
}
for range items {
if err := <-ch; err != nil {
return err2
}
}
return nil
}
func main() {
fmt.Println(process([]int{-1, -2, -3, -4}))
time.Sleep(50 * time.Millisecond)
p := pprof.Lookup("goroutineleak")
if err := p.WriteTo(io.Discard, 0)3; err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println("goroutines:", runtime.NumGoroutine())
fmt.Println("leaked:", p.Count())
}- 1Unbuffered. Make it len(items), and every send completes.
- 2After this line no one reads ch, and the other 3 senders stay blocked.
- 3This call runs the detection: a garbage collection that traces from running goroutines.
| the channel is | printed | status |
|---|---|---|
| A local variable | goroutines: 4, leaked: 3 | Found |
| A global variable | goroutines: 4, leaked: 0 | Missed |
- The profile cannot report a primitive that a global, or a running goroutine, can reach.
- So watch the goroutine count as well. It catches both, without a location.
- For a test that uses this profile, see G12.
goroutineleak profile: total 11
1 @ 0xcb6be0a 0xcb0389c 0xcb03497 0xcbccade 0xcb71f41
# 0xcbccadd main.worker+0x1d2 main.go:12- 1One goroutine leaked.
- 2The function it is stuck in. The line is the send.
A leak is a goroutine that can never wake. The leak profile finds the case where nothing can reach what it waits for.
// Watchdog cancels a context when no beat arrives within limit. A failed
// test of this code usually sleeps for real time and still flakes.
type Watchdog struct {
mu sync.Mutex
timer *time.Timer
limit time.Duration
}
// Watch returns a context that ends after limit passes with no Beat.
func Watch(ctx context.Context, limit time.Duration) (
context.Context, *Watchdog, context.CancelCauseFunc,
) {
ctx, cancel := context.WithCancelCause(ctx)
w := &Watchdog{limit: limit}
w.timer = time.AfterFunc(limit, func() { cancel(ErrSilent) })1
return ctx, w, cancel
}
// Beat restarts the limit.
func (w *Watchdog) Beat() {
w.mu.Lock()
defer w.mu.Unlock()
w.timer.Reset(w.limit)
}
// Stop releases the timer.
func (w *Watchdog) Stop() {
w.mu.Lock()
defer w.mu.Unlock()
w.timer.Stop()
}- 1Real time would make the test slow and flaky. A bubble makes this timer fake.
func TestWatchdog(t *testing.T) {
synctest.Test1(t, func(t *testing.T) {
const limit = 5 * time.Second
ctx, w, cancel := Watch(t.Context(), limit)
defer cancel(nil)
defer w.Stop()
synctest.Sleep(4 * time.Second)2
w.Beat()
synctest.Sleep(4 * time.Second)
if err := ctx.Err(); err != nil {
t.Fatalf("8 s in, one beat at 4 s: %v", err)
}
synctest.Sleep(time.Second)
if got := context.Cause(ctx)3; !errors.Is(got, ErrSilent) {
t.Fatalf("after the limit: cause %v", got)
}
})
}- 1Starts a bubble. The time package in this function uses a fake clock.
- 2New in Go 1.27: time.Sleep, then synctest.Wait, so each goroutine has settled.
- 3The timer has run, because Sleep waited for every goroutine to block.
panic: deadlock: all goroutines in bubble are blocked [recovered, repanicked]
goroutine 21 [chan send (durable)1, synctest bubble 1]:- 1Durable: only the bubble can wake it. So the test fails at once.
A mutex wait is not durable. A bubble does not advance time past it, because a goroutine outside the bubble could release the mutex.
Inside a bubble the clock jumps when every goroutine blocks. The test is exact, it takes no real time, and a stuck goroutine fails it.
| grader check | hazard it provokes | -race on your tests | panel |
|---|---|---|---|
| 100 parallel sets of one key | Concurrent map writes: the server dies and the rest of the run fails. | Reports | C |
| 100 parallel deletes: exactly one wins | Check-then-act: read the key, then delete it, under two locks. | Silent if each step locks | A |
| 100 parallel increments: none is lost | A lost update: a commit that does not compare what it read. | Silent if each step locks | A |
| 100 parallel writes in one transaction | A slice or map in the transaction with no lock of its own. | Reports | C, D |
| 100 parallel commits: exactly one wins | Check-then-act on the transaction state. | Silent if each step locks | A |
| 100 parallel rollbacks | A write that reaches the store before commit. | A logic bug, not a race | A |
See the grader for how the gate works. A race can hide on one run, so run it 3 times.
The grader runs 100 requests through one gate, so a window of microseconds opens on every run. Race-free memory is not enough to pass.
| since | what changed | what it means here |
|---|---|---|
| 1.6 | Best-effort detection of concurrent map misuse. | The fatal error in panel C. Go 1.8 added write and iterate. |
| 1.22 | Each loop iteration has new variables. | The classic captured loop variable is gone at go 1.22 or later. Vet stops the report. |
| 1.24 | copylocks reports a lock in a 3-clause for variable. testing/synctest as an experiment. | Per-iteration copies made this a new way to copy a lock. |
| 1.25 | testing/synctest is generally available. sync.WaitGroup.Go. Vet reports a misplaced WaitGroup.Add. | wg.Go removes the miscount and the late Add. |
| 1.26 | goroutineleak profile as an experiment. | Built behind GOEXPERIMENT=goroutineleakprofile. |
| 1.27 | goroutineleak is generally available, also at /debug/pprof/goroutineleak. synctest.Sleep. Stack dumps print pprof labels. | Run the profile in production. Panel H shows the labels. Turn labels off with tracebacklabels=0 if they hold sensitive data. |
| when | the moment | what to do or say |
|---|---|---|
| build | A read-then-write crosses two store calls. | Add one store method that holds the lock over both. |
| build | A method needs a lock that its caller holds. | Split a private helper that assumes the lock. Name it clearly. |
| build | A test hangs. | Send SIGQUIT. The dump shows the bracket for each goroutine. Read it as in panel H. |
| build | A test uses a timer. | Use synctest, not a real sleep. |
| talk | "Your tests pass with -race. Are you done?" | No. That covers memory on the paths that ran. I also count an invariant under load. |
| talk | "The service hangs in production." | Get the goroutine profile at debug=2 and the goroutineleak profile. Sort goroutines by bracket. |
| talk | "Memory grows slowly." | Watch the goroutine count. Each leak keeps its stack and everything it references. |
| talk | "Two services call each other and hang." | The same cycle as panel H, across a network. Deadlines break it. |
Race-free is the minimum. I also state my invariant and count it in a test, because the logic can be wrong under correct locks.
0 of 10 known
Predict the output.
package main import "fmt" func main() { ch := make(chan int) ch <- 1 fmt.Println(<-ch) }Predict the output.
package main import ( "fmt" "sync" ) type cache struct { mu sync.Mutex m map[string]int } func (c *cache) get(k string) int { c.mu.Lock() defer c.mu.Unlock() return c.m[k] } func (c *cache) incr(k string) { c.mu.Lock() defer c.mu.Unlock() c.m[k] = c.get(k) + 1 } func main() { c := &cache{m: map[string]int{}} c.incr("hits") fmt.Println(c.m["hits"]) }Predict the output.
package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() fmt.Println("one worker") }() wg.Wait() }Predict the output.
package main import ( "fmt" "sync" ) func main() { defer func() { fmt.Println("recovered:", recover()) }() var wg sync.WaitGroup wg.Add(1) wg.Done() wg.Done() }Predict the output.
// The same deadlock as a plain send, but one other goroutine is alive. package main import ( "fmt" "io" "os" "runtime/pprof" "time" ) func main() { go func() { time.Sleep(200 * time.Millisecond) fmt.Println("200 ms later: no deadlock report") p := pprof.Lookup("goroutineleak") if err := p.WriteTo(io.Discard, 0); err != nil { fmt.Println(err) } fmt.Println("leaked:", p.Count()) os.Exit(3) }() ch := make(chan int) ch <- 1 }Predict the output. There is no -race flag here.
// No -race here. The map itself notices the second writer. package main import "sync" func main() { m := map[int]int{} var wg sync.WaitGroup for g := range 4 { wg.Go(func() { for i := 0; ; i++ { m[i%64] = g } }) } wg.Wait() }Predict the output. Items below 0 give an error.
// The first bad item returns early, and the other workers block on send. package main import ( "errors" "fmt" "io" "os" "runtime" "runtime/pprof" "time" ) func process(items []int) error { ch := make(chan error) for _, it := range items { go func() { if it < 0 { ch <- errors.New("bad item") return } ch <- nil }() } for range items { if err := <-ch; err != nil { return err } } return nil } func main() { fmt.Println(process([]int{-1, -2, -3, -4})) time.Sleep(50 * time.Millisecond) p := pprof.Lookup("goroutineleak") if err := p.WriteTo(io.Discard, 0); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Println("goroutines:", runtime.NumGoroutine()) fmt.Println("leaked:", p.Count()) }Predict the output. The only change is that ch is now a global.
// The same leak, but a global variable can still reach the channel. package main import ( "errors" "fmt" "io" "os" "runtime" "runtime/pprof" "time" ) var ch = make(chan error) func process(items []int) error { for _, it := range items { go func() { if it < 0 { ch <- errors.New("bad item") return } ch <- nil }() } for range items { if err := <-ch; err != nil { return err } } return nil } func main() { fmt.Println(process([]int{-1, -2, -3, -4})) time.Sleep(50 * time.Millisecond) p := pprof.Lookup("goroutineleak") if err := p.WriteTo(io.Discard, 0); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Println("goroutines:", runtime.NumGoroutine()) fmt.Println("leaked:", p.Count()) }Predict the output. Vet reports this program, but it still builds.
// Vet rejects this program, so it lives where ./... does not reach it. package main import ( "fmt" "sync" ) type counter struct { mu sync.Mutex n int } func (c counter) snapshot() int { c.mu.Lock() defer c.mu.Unlock() return c.n } func main() { c := counter{} c.mu.Lock() fmt.Println(c.snapshot()) c.mu.Unlock() }Predict the output. The build line sets this file to Go 1.21.
//go:build go1.21 // The build line sets this file's language version to Go 1.21, so the loop // has one i. A go.mod file with go 1.21 or older does the same. package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup got := make([]int, 3) for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done() got[0] = i }() } wg.Wait() fmt.Println(got[0]) }
- exit code
- 2 for a fatal error; 66 for a race report.
- lost appends
- 8,753 to 8,931 of 10,000 items kept, 5 runs.
- leak profile
- 0.7 ms at 16 MiB of live heap; 2.6 ms at 512 MiB. It runs a garbage collection.
- fake time
- 9 s of test time in 0.1 ms of real time.
Go 1.27.3, 8-core Intel i9 laptop, median of 5 profiles, on a busy machine. Use these as orders of magnitude.