Goroutine — lightweight concurrency primitive. Thread — OS-level execution unit.
Key differences:
1// Goroutine-based concurrent processing2func processConcurrently(items []Item) []Result {3 results := make([]Result, len(items))4 var wg sync.WaitGroup56 for i, item := range items {7 wg.Add(1)8 go func(i int, item Item) {9 defer wg.Done()10 results[i] = process(item)11 }(i, item)12 }13 wg.Wait()14 return results15}
When to use goroutines:
When to use threads:
Common mistakes:
runtime.LockOSThread() unnecessarily.