package
0.0.0-20250206045204-45fcc3025d35
Repository: https://github.com/romangurevitch/concurrencyworkshop.git
Documentation: pkg.go.dev

# README

Understanding Go's errgroup Package: Group

The errgroup package in Go provides a straightforward way to manage the lifecycle of a group of goroutines, and their associated error handling.

drawing

Table of Contents

  1. Introduction to Group
  2. Usage of Group
  3. Use Cases
  4. Common Pitfalls
  5. Best Practices
  6. Resources

Introduction to Group

The errgroup.Group type provides synchronisation, error propagation, and Context cancellation for groups of goroutines working on sub-tasks of a common task.

Usage of Group

g, ctx := errgroup.WithContext(context.Background())

g.Go(func() error {
    // Your code here
    return nil  // return an error if something goes wrong
})

// Wait for all goroutines to finish and collect any errors
err := g.Wait()

Examples and tests

See package

Use Cases

  • Concurrent Error Handling:
    • Executing multiple goroutines and aggregating their errors.
  • Context Propagation:
    • Propagating context and cancellation signals across a group of goroutines.

Common Pitfalls

  • Error Ignorance:
    • Ignoring errors returned by Group.Go.
  • Misusing Context:
    • Misusing the context returned by errgroup.WithContext can lead to unintended behavior.
      For instance, storing values in the context that are supposed to be accessed by goroutines may lead to race conditions if not handled properly.

Best Practices

  • Error Handling:
    • Always handle errors returned by Group.Go.
  • Context Usage:
    • Use the context returned by errgroup.WithContext to propagate cancellation.

Resources