Includes solved 02-worker-pool and 09-safe-counter (mutex, atomic, sharded). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GbnJj9ZqEx9nUvzkjdwfMq
33 lines
675 B
Go
33 lines
675 B
Go
// SPOT THE LEAK. Run it — it prints goroutine counts. Explain why the number
|
|
// grows, then fix it with a one-character-ish change.
|
|
package main
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"runtime"
|
|
"time"
|
|
)
|
|
|
|
func fetch() (string, error) {
|
|
ch := make(chan string)
|
|
go func() {
|
|
time.Sleep(50 * time.Millisecond) // pretend slow upstream
|
|
ch <- "body"
|
|
}()
|
|
select {
|
|
case body := <-ch:
|
|
return body, nil
|
|
case <-time.After(10 * time.Millisecond): // timeout fires first
|
|
return "", errors.New("timeout")
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
for i := 0; i < 100; i++ {
|
|
fetch()
|
|
}
|
|
time.Sleep(200 * time.Millisecond)
|
|
fmt.Println("goroutines still alive:", runtime.NumGoroutine()) // expected: 1
|
|
}
|