Documentation
¶
Overview ¶
Package cancelgroup provides a synchronization primitive similar to sync.WaitGroup, but with built-in support for cancellation via context.Context.
It is useful for managing a set of goroutines that need to be canceled and waited for as a group.
Example ¶
package main
import (
"fmt"
"time"
"github.com/your/module/cancelgroup"
)
func main() {
g := cancelgroup.New()
// Start a worker
g.Go(func() {
for {
select {
case <-g.Context().Done():
fmt.Println("worker stopped")
return
default:
fmt.Println("worker running...")
time.Sleep(200 * time.Millisecond)
}
}
})
time.Sleep(1 * time.Second)
// Cancel all workers
g.Cancel()
// Wait for them to stop
g.Wait()
fmt.Println("all workers stopped")
}
Package cancelgroup provides a WaitGroup-like synchronization primitive that also supports cancellation via context.Context.
It allows you to run goroutines that can be canceled as a group, making it easier to coordinate shutdown and resource cleanup.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is similar to sync.WaitGroup but comes with a cancellable context. It can be used to launch goroutines, wait for their completion, and cancel them all at once.
func WithContext ¶
WithContext creates a new Group with a parent context. Cancelling the parent will also cancel the group.
func (*Group) Cancel ¶
func (g *Group) Cancel()
Cancel signals cancellation to all goroutines launched under this group.
func (*Group) Done ¶
func (g *Group) Done()
Done decrements the Group's counter (same as sync.WaitGroup.Done).
func (*Group) Go ¶
func (g *Group) Go(f func())
Go runs the given function in a new goroutine and tracks it in the group. It's a convenience method equivalent to calling Add(1) before launching the goroutine and Done() when it finishes.
The function f should respect the group's context for cancellation and must not panic.