If you’re searching for how to use go routines in Golang, you’re not alone. “Go routines” is one of the most commonly searched terms when learning about goroutines — Go’s built-in way of handling concurrency. This guide covers what go routines are, how to use them properly, and the most common mistakes developers make when working with them.
What Are Go Routines?
Go routines are lightweight threads managed by the Go runtime. They’re created using the go
keyword and allow you to run functions concurrently with minimal overhead.
go myFunction()
Goroutines are cheaper than threads and can scale by the thousands, making them ideal for tasks like I/O operations, background jobs, and real-time services.
Basic Example of a Go Routine
package main import ( "fmt" "time" ) func sayHello() { fmt.Println("Hello from goroutine") } func main() { go sayHello() time.Sleep(1 * time.Second) // Give goroutine time to finish fmt.Println("Main function done") }
Notice the time.Sleep
. Without it, the program might exit before the goroutine finishes.
Common Mistakes with Go Routines
1. Forgetting to Wait for Goroutines
If your main function exits, running goroutines are killed. Always use synchronization like sync.WaitGroup
to wait.
var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() doSomething() }() wg.Wait()
2. Capturing Loop Variables
This classic mistake happens when launching goroutines inside a loop.
❌ Incorrect:
for i := 0; i < 5; i++ {
go func() {
fmt.Println(i)
}()
}
✅ Correct:
for i := 0; i < 5; i++ {
i := i // capture value
go func() {
fmt.Println(i)
}()
}
3. Ignoring Error Handling
Errors inside goroutines aren’t caught unless explicitly passed back to the main function. Use channels to capture them.
errChan := make(chan error)
go func() {
if err := doSomething(); err != nil {
errChan <- err
}
}()
if err := <-errChan; err != nil {
log.Fatal(err)
}
4. Deadlocks and Race Conditions
Improper channel use or missing synchronization can lead to deadlocks. Always close channels properly and use -race
when testing.
Best Practices When Using Go Routines
- Use WaitGroups to wait for goroutines
- Use context.Context to manage timeouts and cancellations
- Use channels for communication and error propagation
- Use the race detector:
go test -race
- Avoid starting unbounded goroutines (e.g., in HTTP handlers)
Idiomatic Goroutine Termination
When you need to cancel goroutines safely, use context.WithCancel
or context.WithTimeout
.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(ctx context.Context) {
for {
select {
case <- ctx.Done():
fmt.Println("Goroutine stopped")
return
default:
// do work
}
}
}(ctx)
When Not to Use Go Routines
- If you don’t control their lifecycle (e.g., infinite background jobs)
- If you’re not handling errors or panics inside them
- If you don’t need concurrency—goroutines add complexity
Conclusion
Go routines are one of the most powerful features in Golang—but with great power comes great responsibility. Use them wisely, watch for common pitfalls like loop variable capture, and manage lifecycle and errors using contexts and channels. If used correctly, they’ll help you write highly concurrent and efficient applications.
Frequently Asked Questions about Go Routines
What is a go routine in Golang?
A go routine is a lightweight thread managed by the Go runtime. It’s used to run functions concurrently using the go
keyword.
How do I wait for all go routines to finish?
You can use the sync.WaitGroup
type to wait for multiple goroutines to complete before continuing execution.
How do I handle errors inside a goroutine?
Errors in goroutines must be explicitly sent to a channel and handled by the main thread or another monitoring goroutine.
Why is my goroutine not running?
If your main function exits before the goroutine finishes, it may be terminated prematurely. Use time.Sleep
(for quick demos) or sync.WaitGroup
in real apps to ensure proper completion.
Can goroutines cause memory leaks?
Yes. If you forget to cancel them or leave them waiting on blocked channels, they can consume memory and CPU indefinitely.
Leave a Reply