Goroutines
What you will learn
- start goroutines and wait for completion;
- return errors through an explicit path;
- prevent common goroutine leaks;
A goroutine is a function executing concurrently with other goroutines in the same program.
Start one with the go keyword:
go sendReport()
The call is scheduled and the current goroutine continues immediately. The runtime manages goroutines and maps them onto a smaller or equal number of operating-system threads as needed.
The program does not wait automatically
func main() {
go fmt.Println("hello from a goroutine")
}
This program may finish before the new goroutine prints anything. When main returns, the process ends and all remaining goroutines stop.
Use an explicit coordination tool rather than time.Sleep:
func main() {
done := make(chan struct{})
go func() {
fmt.Println("work complete")
close(done)
}()
<-done
}
Receiving from done blocks until it is closed.
Anonymous goroutines
go func(message string) {
fmt.Println(message)
}("processing started")
Passing values as parameters makes the data captured by the goroutine explicit.
Errors do not return to the caller
Once a function runs in another goroutine, its return values do not return to the function that started it. Send a result through a channel, store it safely, or use a coordination helper designed to collect errors.
result := make(chan error, 1)
go func() {
result <- doWork()
}()
if err := <-result; err != nil {
log.Println("work failed:", err)
}
Panics stay in the process
An unrecovered panic in any goroutine normally crashes the whole program. A recover call only catches a panic in the same goroutine, and only when called from a deferred function.
Do not use recovery as routine error handling. Prefer returning errors through a defined result path.
Goroutine leaks
A goroutine leaks when it remains blocked or running after nobody needs its result. Common causes include:
- sending to a channel with no receiver;
- waiting on a channel that is never closed;
- retrying forever without cancellation;
- starting background work per request without a stop path.
Leaked goroutines retain their stacks and references, so they can become a production memory problem.
Practice
Run three functions concurrently. Each should send a message to a channel when complete. Make main wait for all three messages without using time.Sleep.
Summary
gostarts concurrent execution but does not make the caller wait.- Goroutine errors need an explicit communication path.
- Blocked sends, receives, or missing cancellation commonly leak goroutines.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.