Introduction
Modern computers do many things at once, and real programs often have to as well: a web server answers thousands of requests, a program downloads many files, an app calculates in the background while it keeps the screen alive. Go was designed for this. Its tool is the goroutine, a function that runs at the same time as the rest of your code, together with the channel, a safe way for goroutines to talk. Go's idea is: do not share memory by communicating, communicate to share memory. In this lesson you will start goroutines, send values between them and wait for them to finish.
How it works
Putting the keyword go in front of a function call starts it as a goroutine. The call returns at once, and the function runs alongside the rest of the program. Goroutines are very light, so a program can run thousands. When main returns, the program ends, even if goroutines are still running, so you need a way to wait for them.
A channel is a pipe with a type: ch := make(chan int). ch <- 5 sends a value and x := <-ch receives one. On an ordinary (unbuffered) channel, a send waits until another goroutine is ready to receive, and a receive waits until a value is sent. This makes channels a way to wait too:
ch := make(chan int)
go func() {
ch <- 42
}()
fmt.Println(<-ch)
A buffered channel, make(chan int, 3), has room for three values, so sends do not wait until it is full. When a sender has nothing more to send, it calls close(ch). A receiver can then use for v := range ch, which reads values until the channel is closed and empty. Only the sender should close a channel, and sending on a closed channel stops the program.
To wait for several goroutines, use a sync.WaitGroup. Call wg.Add(1) before starting each goroutine, wg.Done() when it finishes (often with defer), and wg.Wait() to wait until the counter is zero.
When goroutines change the same variable, you get a data race and the result is wrong. A sync.Mutex fixes it: mu.Lock() before touching the data and mu.Unlock() after, so only one goroutine at a time is inside. Channels often remove the need for locks, because the data belongs to one goroutine at a time.
A select statement waits on several channel operations and runs the case that is ready first. With a default case it does not wait at all, which makes a quick check possible:
select {
case v := <-ch:
fmt.Println(v)
default:
fmt.Println("nothing yet")
}
Goroutines run in an order the program does not control. To keep the output the same every time, collect the results and print them in a fixed order, as the exercises do.
Example
package main
import (
"fmt"
"sync"
)
func sum(nums []int, out chan<- int) {
total := 0
for _, v := range nums {
total += v
}
out <- total
}
func main() {
ch := make(chan int)
go func() {
ch <- 42
}()
fmt.Println(<-ch)
nums := []int{1, 2, 3, 4, 5, 6}
left := make(chan int)
right := make(chan int)
go sum(nums[:3], left)
go sum(nums[3:], right)
fmt.Println(<-left, <-right)
buffered := make(chan string, 3)
buffered <- "a"
buffered <- "b"
buffered <- "c"
close(buffered)
for s := range buffered {
fmt.Print(s, " ")
}
fmt.Println()
var wg sync.WaitGroup
var mu sync.Mutex
counter := 0
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
counter++
mu.Unlock()
}()
}
wg.Wait()
fmt.Println("counter:", counter)
empty := make(chan int)
select {
case v := <-empty:
fmt.Println("got", v)
default:
fmt.Println("nothing yet")
}
}Line by line
- The first goroutine sends 42 on an unbuffered channel, and
<-chinmainwaits for it. sumis run twice as a goroutine, once for each half of the slice; each sends its total on its own channel, andmainreads both.- A buffered channel with room for 3 values is filled, closed and then read with
range. - 100 goroutines add 1 to the same counter. The WaitGroup waits for all of them, and the Mutex makes sure no change is lost.
selectwithdefaultfinds the empty channel and takes the default case.
Expected result
42
6 15
a b c
counter: 100
nothing yet
In the real world
Go is used for servers because goroutines make concurrent code simple: a web server starts a goroutine for every request. Pipelines of goroutines connected by channels process data in steps, such as reading, converting and saving. Worker pools limit how much work runs at once. The same ideas appear in the tools that run on cloud systems.
Common mistakes
- Forgetting to wait for goroutines, so
mainends first. - Reading from a channel that nobody sends to, which waits for ever and ends with a deadlock error.
- Closing a channel from the receiver, or closing it twice.
- Changing shared data without a Mutex, which gives wrong results.
- Expecting goroutines to run in a fixed order. They do not.
Best practices
- Start goroutines only when you know how they will finish.
- Let the sender close the channel, and use
rangeto read until it is closed. - Keep shared data to a minimum, and protect it with a Mutex when you must.
- Collect results and print them in a fixed order.
Summary
go f() runs f at the same time as the caller. Channels carry values between goroutines, and an unbuffered send and receive wait for each other. A sender closes a channel when it is done and the receiver reads it with range. A WaitGroup waits for goroutines, a Mutex protects shared data, and select chooses a ready channel.
Quick check
Key takeaways
- go f() starts f as a goroutine; goroutines are cheap, so a program can have thousands.
- A channel sends values between goroutines; a send and a receive wait for each other on an unbuffered channel.
- Wait with a WaitGroup, protect shared data with a Mutex, and close a channel to say that nothing more will come.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.