Goroutines
A goroutine is a function executing concurrently, started with go f(). The runtime multiplexes many goroutines onto OS threads. They are cheaper than threads, but they still need a way to stop and to share data safely.
Detailed Explanation
go handle(req) returns immediately. handle runs while the caller continues. That is all go does: schedule a call. It does not wait, it does not return a handle, and it does not recover a panic in that function unless you defer recover inside it.
They are not threads. The Go scheduler parks a goroutine that is waiting on a channel, a mutex, or I/O, and runs another on the same OS thread. A blocking C call or a tight CPU loop without function calls can stall a thread; the runtime grows GOMAXPROCS worker threads as needed. You still should not start an unbounded number of goroutines per request without a limit (a worker pool or a semaphore channel).
Stacks start small and grow. A new goroutine gets a small stack (on the order of a couple of KiB) that the runtime copies to a larger one when needed. That is why millions of waiting goroutines can exist, and why a huge [1 << 20]byte local in each one is still a problem.
No join without you building one. go f() does not give you a future. Use sync.WaitGroup, a channel receive, or errgroup to wait. If main returns, the process exits and leftover goroutines die mid-work.
Panic is per goroutine. An unrecovered panic crashes the process. Wrap workers you do not trust with defer recover, and do not assume http.Server's recover covers go you started inside a handler.
What it costs. Starting a goroutine is cheap compared to pthread_create. The expensive part is what they share. A data race is a bug. A leaked goroutine that blocks on a channel nobody closes is a memory leak. Always know how each goroutine will finish.
Code Examples
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("hello")
}()
wg.Wait()
}func handleAll(ids []int, fn func(int)) {
var wg sync.WaitGroup
for _, id := range ids {
wg.Add(1)
go func(id int) {
defer wg.Done()
fn(id)
}(id)
}
wg.Wait()
}Common Gotchas
`main` exiting kills other goroutines
wait if their work must finish.
A panic in a child goroutine crashes the process
recover at the edge of that goroutine.
Unbounded `go` per request can exhaust memory
cap concurrency.
Loop variables are per-iteration since Go 1.22
passing `id` as an argument is still the clearest form.