Goroutines and channels
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Concurrency is built in
Go was designed for programs that do many things at the same time: serve thousands of requests, call several APIs at once, process a queue of jobs. The language gives you two simple tools for this. A goroutine is a function running independently, and a channel is a pipe for sending values between goroutines.
Starting a goroutine
Put the keyword go in front of a function call, and it runs concurrently with the rest of your program.
go checkStock("tea") // starts and returns immediately
Goroutines are very cheap, with an initial stack of a few kilobytes, so you can have tens of thousands of them. But there is a catch. When main returns, the program exits, and any goroutines still running are killed without warning. You need a way to wait for them and to collect their results. That is what channels are for.
Channels
A channel is created with make(chan Type). You send with ch <- value and receive with value := <-ch. An unbuffered channel makes both sides wait for each other: a send blocks until someone receives, and a receive blocks until someone sends. That meeting point is how goroutines synchronise.
package main
import (
"fmt"
"sync"
"time"
)
type Result struct {
Job int
Value int
}
func worker(id int, jobs <-chan int, results chan<- Result, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
time.Sleep(50 * time.Millisecond) // pretend to do real work
results <- Result{Job: job, Value: job * job}
}
fmt.Println("worker", id, "finished")
}
func main() {
jobs := make(chan int, 10)
results := make(chan Result, 10)
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Add(1)
go worker(id, jobs, results, &wg)
}
for j := 1; j <= 9; j++ {
jobs <- j
}
close(jobs) // tells the workers: no more jobs
// close results once every worker is done
go func() {
wg.Wait()
close(results)
}()
sum := 0
for r := range results {
sum += r.Value
}
fmt.Println("sum of squares:", sum)
}
The sum is always 285 (1 + 4 + 9 + ... + 81). The order of the "worker finished" lines varies from run to run, because the goroutines are scheduled independently.
How the worker pool works
We create two channels: jobs for incoming work and results for outgoing answers. Three workers each loop over jobs with range, which keeps receiving until the channel is closed and empty. The main goroutine sends nine jobs, then closes jobs to signal there is no more work. The workers finish their loops and call wg.Done().
A sync.WaitGroup counts goroutines: Add(1) before starting one, Done() when it ends, and Wait() blocks until the count reaches zero. In Go 1.25 there is a convenience method, wg.Go(func() { ... }), that does the Add and Done for you. The explicit form shown above works in all versions and makes the mechanics clear.
A separate goroutine waits for the group and then closes results. This is important: if nobody closes results, the for r := range results loop in main would wait forever.
The types <-chan int and chan<- Result in the worker's signature are directional channels. The first can only be received from, the second only sent to. The compiler then stops you from misusing them, and it documents the intent.
Buffered channels
make(chan int, 10) creates a channel with room for ten values. Sends only block when the buffer is full, and receives only block when it is empty. Buffers smooth out bursts, but do not use them to hide design problems. An unbuffered channel is the simplest and safest default.
The rules of closing
- Only the sender should close a channel, never the receiver.
- Sending on a closed channel panics. Closing an already closed channel also panics.
- Receiving from a closed channel does not block. You get the zero value, and
v, ok := <-chgivesok == false. - You do not have to close every channel. Close it when receivers need to know that no more values are coming, as with a
rangeloop.
Deadlocks and leaks
If all goroutines are blocked and none can continue, Go detects it and stops with fatal error: all goroutines are asleep - deadlock!. A typical cause is sending on an unbuffered channel when nobody receives:
ch := make(chan int)
ch <- 1 // blocks forever: no receiver
fmt.Println(<-ch)
A goroutine leak is quieter. A goroutine blocked forever on a channel nobody will use again is never cleaned up. In a server, leaks add up until memory runs out. Always know how each goroutine you start will end.
Share memory by communicating
The Go motto is "Do not communicate by sharing memory; share memory by communicating." Instead of several goroutines touching one variable, pass values through channels so that only one goroutine owns the data at a time. Sometimes a mutex is simpler, but channels are a good first instinct.
Common mistakes
- Not waiting for goroutines. The program ends before they run. Use a WaitGroup or channel.
- Closing the channel from the wrong place. Panic on send.
- Forgetting to close a channel that a
rangeloop is reading, so the loop never ends. - Starting goroutines in a loop with a shared variable in Go versions before 1.22. In 1.22 and later each iteration has its own variable, so this problem is gone.
- Unbounded goroutines. A million goroutines for a million jobs may overwhelm a database. A worker pool limits that.
Try it yourself
Write a program that has a producer goroutine sending the numbers 1 to 20 on a channel, and two consumer goroutines that receive the numbers and send the doubled value to a results channel. Collect all results in main, sort them, and print them. Make sure that the program does not deadlock, and that it ends cleanly.
package main
import (
"fmt"
"sync"
"time"
)
type Result struct {
Job int
Value int
}
func worker(id int, jobs <-chan int, results chan<- Result, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
time.Sleep(50 * time.Millisecond) // pretend to do real work
results <- Result{Job: job, Value: job * job}
}
fmt.Println("worker", id, "finished")
}
func main() {
jobs := make(chan int, 10)
results := make(chan Result, 10)
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Add(1)
go worker(id, jobs, results, &wg)
}
for j := 1; j <= 9; j++ {
jobs <- j
}
close(jobs) // tells the workers: no more jobs
// close results once every worker is done
go func() {
wg.Wait()
close(results)
}()
sum := 0
for r := range results {
sum += r.Value
}
fmt.Println("sum of squares:", sum)
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account