Goroutine — lightweight concurrency primitive. Thread — OS-level execution unit.
Memory:
Scheduling:
Cost:
1// Efficient goroutine usage2func fanOut(items []Item) []Result {3 results := make([]Result, len(items))4 var wg sync.WaitGroup5 for i, item := range items {6 wg.Add(1)7 go func(i int, item Item) {8 defer wg.Done()9 results[i] = process(item)10 }(i, item)11 }12 wg.Wait()13 return results14}
When to use goroutines:
When to use threads:
Common mistakes:
runtime.LockOSThread() unnecessarily.