Goroutines and channels
Concurrency is cheap in Go, but coordination is still your responsibility.
What you will be able to do
- Use context.Context for cancellation and deadlines.
- Close a channel only from the sender.
- Run the race detector in tests.
In plain English
A goroutine is a lightweight function running concurrently. Channels pass values between goroutines; sync.WaitGroup waits for a group; context cancels work. Never leave a goroutine blocked forever.
func FetchAll(ctx context.Context, urls []string) ([]string, error) {
results := make(chan string, len(urls))
var group sync.WaitGroup
for _, url := range urls {
group.Add(1)
go func(url string) {
defer group.Done()
body, err := fetch(ctx, url)
if err == nil {
results <- body
}
}(url)
}
group.Wait()
close(results)
var bodies []string
for body := range results {
bodies = append(bodies, body)
}
return bodies, nil
}Your turn
MediumWait for workers
Start two goroutines that print their id, and use a WaitGroup to wait for both.
GO · starter
var group sync.WaitGroupCheck your understanding before moving on.
Knowledge checkQuestion 1
Who should close a channel?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.