Basic Usage
Thego keyword launches a function call as a goroutine, allowing it to execute concurrently with the calling code:
Goroutines are extremely lightweight compared to OS threads. You can easily run thousands or even millions of goroutines in a single program.
Key Concepts
Synchronous vs Asynchronous Execution
- Synchronous:
f("direct")- The function runs and completes before the next line executes - Asynchronous:
go f("goroutine")- The function starts running concurrently, and control returns immediately
Anonymous Function Goroutines
You can launch anonymous functions as goroutines:Waiting for Completion
The example usestime.Sleep() to wait for goroutines, but this is not robust for production code:
Performance Characteristics
| Feature | Goroutine | OS Thread |
|---|---|---|
| Stack size | ~2KB (growable) | ~1MB (fixed) |
| Creation time | Microseconds | Milliseconds |
| Context switch | Nanoseconds | Microseconds |
| Maximum count | Millions | Thousands |
Common Patterns
Fire and Forget
Concurrent Processing
Best Practices
- Always handle goroutine completion - Don’t let goroutines run indefinitely without a way to signal completion
- Use proper synchronization - Prefer WaitGroups or channels over
time.Sleep() - Avoid goroutine leaks - Ensure all goroutines can exit when no longer needed
- Pass parameters explicitly - Avoid relying on closure capture of loop variables
Related Topics
- Channels - Communication between goroutines
- WaitGroups - Waiting for multiple goroutines
- Worker Pools - Managing concurrent workers
- Select - Multiplexing channel operations