Documentation ¶
Overview ¶
Package workgroup provides a mechanism for controlling the lifetime of a set of related goroutines.
Index ¶
Examples ¶
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
}
A Group manages a set of goroutines with related lifetimes. The zero value for a Group is fully usable without initialisation.
func (*Group) Add ¶
Add adds a function to the Group. The function will be executed in its own goroutine when Run is called. Add must be called before Run.
func (*Group) AddContext ¶ added in v1.0.0
AddContext adds a function taking a context.Context to the group. The function will be executed in its own goroutine when Run is called. The context supplied to the function will be canceled when the group exits. AddContext must be called before Run.
func (*Group) Run ¶
Run executes each function registered via Add in its own goroutine. Run blocks until all functions have returned. The first function to return will trigger the closure of the channel passed to each function, who should in turn, return. The return value from the first function to exit will be returned to the caller of Run.
Example ¶
package main import ( "fmt" "time" "github.com/projectcontour/contour/internal/workgroup" ) func main() { var g workgroup.Group a := func(stop <-chan struct{}) error { defer fmt.Println("A stopped") <-time.After(100 * time.Millisecond) return fmt.Errorf("timed out") } g.Add(a) b := func(stop <-chan struct{}) error { defer fmt.Println("B stopped") <-stop return nil } g.Add(b) err := g.Run() fmt.Println(err) }
Output: A stopped B stopped timed out
Example (MultipleListeners) ¶
package main import ( "fmt" "net" "net/http" "github.com/projectcontour/contour/internal/workgroup" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprintln(w, "Hello, HTTP!") }) var g workgroup.Group // listen on port 80 g.Add(func(stop <-chan struct{}) error { l, err := net.Listen("tcp", ":80") // nolint:gosec if err != nil { return err } go func() { <-stop l.Close() }() return http.Serve(l, mux) }) // listen on port 443 g.Add(func(stop <-chan struct{}) error { l, err := net.Listen("tcp", ":443") // nolint:gosec if err != nil { return err } go func() { <-stop l.Close() }() return http.Serve(l, mux) }) g.Run() // nolint:errcheck }
Output:
Example (WithShutdown) ¶
package main import ( "fmt" "time" "github.com/projectcontour/contour/internal/workgroup" ) func main() { var g workgroup.Group shutdown := make(chan time.Time) g.Add(func(<-chan struct{}) error { <-shutdown return fmt.Errorf("shutdown") }) g.Add(func(stop <-chan struct{}) error { <-stop return fmt.Errorf("terminated") }) go func() { shutdown <- <-time.After(100 * time.Millisecond) }() err := g.Run() fmt.Println(err) }
Output: shutdown