~/Effective Tips for Goroutines in Go

Jun 17, 2019


Use goroutines to run concurrent tasks in Go. Launch a goroutine by using the go keyword in front of a function or method call.

Always manage shared data with channels or other synchronization primitives like sync.Mutex to avoid data races.

Example to launch a goroutine:

1
2
3
go func() {
    // do work
}()

Tips:

  1. Avoid launching too many goroutines, as they consume memory. Use worker pools to control concurrency.
  2. Always clean up by signaling when the goroutine should stop. Use done channels or context.Context. Example with context cancellation:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
ctx, cancel := context.WithCancel(context.Background())

go func() {
    for {
        select {
        case <-ctx.Done():
            return
        default:
            // do work
        }
    }
}()
cancel() // to stop goroutine
  1. Capture loop variables correctly inside goroutine functions:
1
2
3
4
5
for i := 0; i < 10; i++ {
    go func(i int) {
        // use i safely
    }(i)
}
  1. Always handle and check for goroutine leaks.

By following these tips, your Go concurrent programs will be more efficient and less prone to subtle bugs.

Tags: [golang] [concurrency]