A goroutine is a lightweight, independently executing function managed by the Go runtime. Unlike operating-system threads, goroutines use small, resizable stacks, making it practical to run many in one address space. section 7.2.1 section 1.2.1
Goroutines enable concurrency: tasks can make progress independently, but they are not guaranteed to execute simultaneously on separate cores. Starting goroutines and communicating between them also has a cost, so concurrency does not guarantee a speedup. section 7.2.1 section 9.3.2
Listing 7.6 parallel.go: Example of a program running goroutines
package main
import (
"fmt"
"time"
)
func printEverySecond(msg string) {
for i := 0; i < 10; i++ {
fmt.Println(msg)
time.Sleep(time.Second)
}
}
func main() {
// Run two goroutines
go printEverySecond("Hello") #1
go printEverySecond("World") #2
var input string
fmt.Scanln(&input) #3
}
Prefix a function call with go to launch it in a new goroutine. This program starts two message printers while main waits for input; launching them does not notify the caller when they finish. section 7.2.2
Plan how each goroutine will finish. Channels communicate data between goroutines; close a channel when writing is complete so its readers know when to stop. Synchronization tools such as sync.WaitGroup can wait for work to finish before returning. section 7.6 section 7.5.3
Listing 7.9 Testing the cache with goroutines
func TestCache_Parallel_goroutines(t *testing.T) {
c := cache.New[int, string]() #1
const parallelTasks = 10 #2
wg := sync.WaitGroup{}
wg.Add(parallelTasks) #2
for i := 0; i < parallelTasks; i++ {
go func(j int) { #3
defer wg.Done()
c.Upsert(4, fmt.Sprint(j)) #4
}(i)
}
wg.Wait() #5
}
This cache test registers ten tasks with a WaitGroup, starts a goroutine for each, calls Done when each finishes, and waits before returning. Passing i as a parameter gives each invocation its own value. section 7.3.1 section 9.7
Waiting for goroutines does not by itself make shared data safe to modify concurrently. A cache used by multiple goroutines needs a concurrency-safe design. section 7.3.1 section 7.0
Explore maze branches concurrently
At an intersection, continue exploring one branch and start goroutines for the others. Channels communicate newly available paths. This can improve performance, but goroutine startup and communication add overhead. section 9.3.2






