Golang Tutorial 14: Channels, select and sync
Buffered and unbuffered channels, closing them, select with timeouts, WaitGroup.Go, a mutex the race detector is happy with, a bounded worker pool and errgroup. Runnable Go 1.27 examples and an exercise at the end.
Tutorial 8 introduced goroutines, a string channel and a WaitGroup. It named mutexes and worker pools but never showed them working, and select wasn't there at all. In this blog we will fill those gaps with code you can run. Level is intermediate. You should be fine with functions, structs and slices (Tutorial 9 covers slices), and you need Go 1.25 or newer because I use WaitGroup.Go. I ran everything here on Go 1.27.3.
Set up a module first.
mkdir tut14 && cd tut14
go mod init example.com/tut14
mkdir -p cmd/basics cmd/race cmd/pool cmd/errgroup
If go mod init and the cmd/ folders look new, Tutorial 13 explains modules and packages.
Unbuffered and buffered channels
An unbuffered channel has no room in it. A send waits until some other goroutine receives, so the two meet at that line. A buffered channel has a few slots. Sends go straight into the slots and only block once they are full.
Closing a channel tells receivers that no more values are coming. A for range over a channel ends when the channel is closed and empty. Receiving from a closed channel never blocks, you get the zero value and ok is false.
select waits on several channel operations and runs whichever is ready first. With time.After as one of the cases you get a timeout. With a default case it never waits at all.
Here is all of that in one file, cmd/basics/main.go.
package main
import (
"fmt"
"time"
)
func main() {
// Unbuffered: the send waits until someone receives.
done := make(chan string)
go func() {
time.Sleep(100 * time.Millisecond)
done <- "worker finished"
}()
fmt.Println(<-done)
// Buffered: sends don't block until the buffer is full.
jobs := make(chan int, 3)
jobs <- 1
jobs <- 2
jobs <- 3
fmt.Println("len:", len(jobs), "cap:", cap(jobs))
// Closing tells the receiver no more values are coming.
close(jobs)
for j := range jobs {
fmt.Println("job", j)
}
v, ok := <-jobs
fmt.Println("after close:", v, ok)
// select with a timeout.
slow := make(chan string)
go func() {
time.Sleep(2 * time.Second)
slow <- "too late"
}()
select {
case msg := <-slow:
fmt.Println(msg)
case <-time.After(500 * time.Millisecond):
fmt.Println("timed out after 500ms")
}
// select with default never blocks.
ch := make(chan int)
select {
case n := <-ch:
fmt.Println("got", n)
default:
fmt.Println("nothing ready, moving on")
}
}
go run ./cmd/basics
worker finished
len: 3 cap: 3
job 1
job 2
job 3
after close: 0 false
timed out after 500ms
nothing ready, moving on
One thing in there is a small leak. Now what happens is, the goroutine that sends "too late" is still blocked on slow when main moves on, because nobody will ever receive. In a short program it doesn't matter. And in a server that does this on every request you slowly pile up stuck goroutines. A buffer of one (make(chan string, 1)) lets that send finish and the goroutine exit, which is the usual fix.
Who closes the channel
The sender only closes, never the receiver. Sending on a closed channel panics, so only the side that knows "I am done sending" should call close. With many senders, a separate goroutine waits for all of them and then closes. You'll see that pattern in the worker pool below.
Forget to close and range waits forever. I wrote this on purpose to show it, and Go was quite clear about it.
jobs := make(chan int, 3)
jobs <- 1
jobs <- 2
// Forgot close(jobs): range waits forever after the second value.
for j := range jobs {
fmt.Println("job", j)
}
job 1
job 2
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
The runtime only catches this when every goroutine is stuck. In a web server there is always some goroutine alive (the listener), so the same bug just hangs one request quietly. That's the harder one to find.
WaitGroup and Mutex
Tutorial 8 used wg.Add(1) and defer wg.Done(). Since Go 1.25 there is wg.Go(func), which does both for you. I'd use it in all new code, it's one less thing to forget.
Now the classic mistake. A thousand goroutines each add one to a plain int.
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.Mutex
n map[string]int
}
func (c *Counter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.n[key]++
}
func main() {
// Broken version: many goroutines writing one int.
var wg sync.WaitGroup
hits := 0
for range 1000 {
wg.Go(func() {
hits++
})
}
wg.Wait()
fmt.Println("unsafe hits:", hits)
// Fixed version with a mutex.
c := Counter{n: map[string]int{}}
for i := range 1000 {
wg.Go(func() {
if i%2 == 0 {
c.Inc("even")
} else {
c.Inc("odd")
}
})
}
wg.Wait()
fmt.Println("safe counts:", c.n)
}
I ran it three time on my Mac.
unsafe hits: 967
safe counts: map[even:500 odd:500]
unsafe hits: 909
safe counts: map[even:500 odd:500]
unsafe hits: 922
safe counts: map[even:500 odd:500]
Never 1000. hits++ is a read, an add and a write, and two goroutines can read the same old value. The mutex version is right every time. Note the mutex sits next to the data it protects, inside the struct, and the method locks it. Callers can't forget.
Then run the broken one with the race detector.
go run -race ./cmd/race
==================
WARNING: DATA RACE
Read at 0x00c000114048 by goroutine 8:
main.main.func1()
.../cmd/race/main.go:25 +0x2c
Previous write at 0x00c000114048 by goroutine 9:
main.main.func1()
.../cmd/race/main.go:25 +0x3c
Line 25 is hits++. The race detector only reports races that really happen while the program runs, so it needs tests or traffic that hit the code. I'd still turn it on for every go test run in CI, the slowdown is worth it.
A small aside on sync.RWMutex. People basically reach for it by default. Use it only when reads are much more than writes and the locked section is not tiny, otherwise a plain Mutex is as fast and simpler.
A bounded worker pool
Starting one goroutine per job is fine for a hundred jobs. For ten thousand calls to an API with a rate limit, it's not. A pool keeps a fixed number of workers reading from one jobs channel.
package main
import (
"crypto/sha256"
"fmt"
"sync"
"time"
)
type result struct {
id int
hash string
}
func work(id int) result {
// Pretend this is a slow call: an API, a file, a query.
time.Sleep(50 * time.Millisecond)
sum := sha256.Sum256(fmt.Appendf(nil, "job-%d", id))
return result{id: id, hash: fmt.Sprintf("%x", sum[:4])}
}
func main() {
const workers = 4
jobs := make(chan int)
results := make(chan result)
var wg sync.WaitGroup
for w := range workers {
wg.Go(func() {
for id := range jobs {
r := work(id)
fmt.Printf("worker %d did job %d\n", w, id)
results <- r
}
})
}
// Close results once every worker has returned.
go func() {
wg.Wait()
close(results)
}()
// Feed the jobs, then close so the workers' range loops end.
go func() {
for id := range 20 {
jobs <- id
}
close(jobs)
}()
start := time.Now()
count := 0
for r := range results {
_ = r
count++
}
fmt.Printf("%d results in %v\n", count, time.Since(start).Round(10*time.Millisecond))
}
worker 1 did job 1
worker 3 did job 3
worker 0 did job 0
worker 2 did job 2
worker 1 did job 4
...
worker 0 did job 18
20 results in 260ms
Twenty jobs of 50ms with four workers is five rounds, so about 250ms. Order changes every run, that is normal.
Three goroutines do the plumbing here and it's worth reading slowly. The workers range over jobs. The feeder sends 20 jobs and closes jobs, which ends the workers' loops. A third goroutine waits on the WaitGroup and closes results, which ends the loop in main. If you put wg.Wait() directly in main before reading results, it deadlocks: workers block sending to results and nobody reads. It's a very easy mistake to make, and the code looks fine when you read it.
errgroup when any failure should stop the rest
The pool above has no error handling. When one job fails and the others should stop, use errgroup from golang.org/x/sync. It's a WaitGroup that collects the first error, cancels a shared context, and can limit how many goroutines run.
go get golang.org/x/sync@latest
That gave me v0.25.0.
package main
import (
"context"
"errors"
"fmt"
"time"
"golang.org/x/sync/errgroup"
)
func check(ctx context.Context, id int) error {
select {
case <-time.After(time.Duration(100+id*20) * time.Millisecond):
case <-ctx.Done():
fmt.Printf("check %d stopped: %v\n", id, ctx.Err())
return ctx.Err()
}
if id == 3 {
return errors.New("check 3: host unreachable")
}
fmt.Printf("check %d ok\n", id)
return nil
}
func main() {
g, ctx := errgroup.WithContext(context.Background())
g.SetLimit(3) // at most 3 checks at the same time
for id := range 8 {
g.Go(func() error {
return check(ctx, id)
})
}
if err := g.Wait(); err != nil {
fmt.Println("first error:", err)
}
}
check 0 ok
check 1 ok
check 2 ok
check 6 stopped: context canceled
check 5 stopped: context canceled
check 4 stopped: context canceled
check 7 stopped: context canceled
first error: check 3: host unreachable
The output surprised me bit at first. Checks 4 to 7 still started, they just saw a cancelled context straight away and returned. g.Go with a limit only waits for a free slot, it doesn't skip work after an error. So the function itself has to watch ctx.Done(), otherwise cancellation does nothing. Context gets its own post next, in Tutorial 15.
Channel or mutex
My rule of thumb. If goroutines hand work or results to each other, use a channel. If they all touch one piece of shared state (a map, a counter, a cache), use a mutex. Trying to protect a map with a channel usually ends up as a slower, harder to read mutex.
Exercise
Change the worker pool so it stops after 350ms even if jobs are left. Collect the results that arrived before the deadline, then tell the workers and the feeder to stop, and print how many results you got. Hint: one stop channel that you close, and a select in both the feeder and the workers.
My version printed got 9 results before the deadline, sum 204 with three workers doing 100ms jobs, and it runs clean under go run -race. Try it before looking up the answer, the sending side is the part people forget.