Go Goroutines
A goroutine is a lightweight thread managed by the Go runtime. They are the core of Go's concurrency model, allowing you to run functions independently and simultaneously.
1. Basic Usage
To run a function in a goroutine, simply add the go keyword before the function call.
2. Synchronization (WaitGroups)
The time.Sleep approach is unreliable. In real apps, we use sync.WaitGroup to wait for all goroutines to finish correctly.
Why use Goroutines over Threads?
- Memory: Goroutines start with only 2KB of stack memory, compared to 1MB or more for OS threads.
- Speed: Switching between goroutines (context switching) is much faster because it happens entirely within the Go runtime, not the OS kernel.
- Scalability: You can easily run hundreds of thousands of goroutines on a single machine where threads would crash it.
Best Practices
- Don't leak them: Always make sure a goroutine has a way to finish.
- No global state: Avoid modifying global variables from multiple goroutines (use channels or mutexes instead).
- Channel communication: Prefer "communicating by sharing" (Channels) over "sharing by communicating" (Mutexes).