Running functions at the same time
So far, every program did one thing at a time, line after line. Concurrency means a program works on several tasks during the same period. A web server, for example, answers many users at once. Go makes this easy with goroutines.
A goroutine is a function call that runs at the same time as the rest of the program. To start one, write go in front of the call. Goroutines are cheap, so a program can start thousands of them.
package main
import (
"fmt"
"time"
)
func say(text string) {
time.Sleep(100 * time.Millisecond)
fmt.Println(text)
}
func main() {
go say("hello from a goroutine")
fmt.Println("main is done")
}
Output:
main is done
The time package is imported for time.Sleep, which pauses for the given time. Here say waits 100 milliseconds before it prints.
The goroutine's message never appeared. go say(...) started the goroutine and went on at once, without waiting. Then main returned, and when main returns, the whole program ends, even if other goroutines are still working.
Waiting with a WaitGroup
To wait for goroutines, use a sync.WaitGroup from the sync package. It is a counter of unfinished jobs, with three methods:
| Method | What it does |
|---|---|
wg.Add(n) | adds n jobs to the counter |
wg.Done() | marks one job as finished |
wg.Wait() | waits until the counter is 0 |
package main
import (
"fmt"
"sync"
)
func count(word string, n *int, wg *sync.WaitGroup) {
defer wg.Done()
*n = len(word)
}
func main() {
var a, b int
var wg sync.WaitGroup
wg.Add(2)
go count("goroutine", &a, &wg)
go count("channel", &b, &wg)
wg.Wait()
fmt.Println(a, b)
}
Output:
9 7
main adds 2 jobs, starts two goroutines, then waits. Each goroutine calls wg.Done() when it ends. defer makes sure this happens even if the function returns early. When both are done, Wait returns and main prints.
The function takes wg as a pointer, *sync.WaitGroup. Without the pointer, each goroutine would get its own copy of the counter. The counter in main would never reach 0, so Go would stop the program with the error fatal error: all goroutines are asleep - deadlock!.
Goroutines in a loop
Often you start one goroutine per item. Give each goroutine its own place for its result, like one index of a slice:
nums := []int{2, 3, 4, 5}
squares := make([]int, len(nums))
var wg sync.WaitGroup
for i, n := range nums {
wg.Add(1)
go func() {
defer wg.Done()
squares[i] = n * n
}()
}
wg.Wait()
fmt.Println(squares)
Output:
[4 9 16 25]
go func() { ... }() starts a function with no name as a goroutine. Since Go 1.22, every turn of the loop has its own i and n, so each goroutine sees the right values.
The order is not fixed
Goroutines do not finish in the order you start them. This program starts five goroutines, and each one prints its number:
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Print(i, " ")
}()
}
wg.Wait()
fmt.Println()
On our runs, it printed 5 1 2 3 4 once and 1 5 2 3 4 another time. Go does not promise any order. That is why the example before stored each result at its own index and printed only after Wait. The output is then the same on every run.
In the exercise, start add as a goroutine for each half of the numbers, then wait for both with the WaitGroup.