Goroutines and Channels: Concurrency Without Losing Your Mind
Launch lightweight concurrent tasks with the go keyword, pass results safely over channels, and avoid deadlocks and race conditions.
You'll learn how go fn() starts a lightweight goroutine, how channels (chan T) pass values safely between concurrent tasks, and how select handles multiple channels or timeouts. Assumes basic Go functions and slices.
1. Doing five things at once
If your server needs to check three external APIs and each one takes 300ms, running them one after another wastes 900ms.
Go makes concurrency cheap. Put the word go in front of any function call, and Go starts a goroutine—a tiny, runtime-managed concurrent task that takes ~2KB of memory (you can run tens of thousands of them on a laptop).
package main
import (
"fmt"
"time"
)
func say(msg string) {
time.Sleep(50 * time.Millisecond)
fmt.Println(msg)
}
func main() {
go say("from goroutine")
fmt.Println("from main")
}If you run that, "from goroutine" never prints. Why? Because main() printed "from main" and immediately exited—and when main() exits, the whole program dies, taking every running goroutine with it.
2. Communicating with channels
Instead of guessing with time.Sleep, use a channel (chan string)—a typed pipe that lets one goroutine send a value (ch <- val) and another wait to receive it (<-ch):
package main
import (
"fmt"
"time"
)
func checkService(name string, ch chan<- string) {
time.Sleep(80 * time.Millisecond)
ch <- name + " is up"
}
func main() {
ch := make(chan string, 3)
go checkService("auth", ch)
go checkService("billing", ch)
go checkService("search", ch)
for i := 0; i < 3; i++ {
fmt.Println(<-ch)
}
}search is up
auth is up
billing is upAll three checks ran in ~80ms total instead of 240ms. And because <-ch blocks until a value arrives, main() naturally waits for all three goroutines before exiting.
Notice chan<- string in the parameter list: that arrow tells Go "this function can only send to ch, never accidentally read from it."
Run go run -race . on your Go code whenever you use goroutines—Go's built-in race detector catches shared-memory bugs immediately.
3. Waiting on whichever finishes first with select
select is like a switch statement for channels—it waits until one of several channels is ready:
select {
case msg := <-ch:
fmt.Println("Got:", msg)
case <-time.After(100 * time.Millisecond):
fmt.Println("Timed out waiting!")
}Common mistakes
| Error / Bug | What it means | Fix |
|---|---|---|
fatal error: all goroutines are asleep - deadlock! | Waiting to receive from a channel nobody will ever send to | Match sends/receives or close(ch) before for v := range ch |
| Goroutines silently cut off | main() returned before goroutines finished | Wait on a channel or sync.WaitGroup |
Data race on a shared map | Two goroutines wrote to the same map at once | Pass results over a channel or protect with sync.Mutex |
Practice
- What happens if
main()starts 3 goroutines and returns without waiting on a channel orWaitGroup?
Answer: The process exits immediately and kills the unfinished goroutines.
What you learned
go fn()launches a lightweight concurrent goroutine.- Channels (
make(chan T)) pass values safely between goroutines and synchronize completion. selectlets you wait on multiple channels or add a cleantime.Aftertimeout.
Video walkthrough
YouTubeClick play to load video (YouTube)