CancelChain 提供并发原语。轻松实现并发启动、顺序取消goroutine。
package main
import (
"context"
"fmt"
"time"
"github.com/mind1949/cancelchain"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
c := cancelchain.WithContext(ctx)
for i := 0; i < 10; i++ {
seq := i
c.Go(func(ctx context.Context) error {
<-ctx.Done()
fmt.Printf("exit goroutine[%d]\n", seq)
return ctx.Err()
})
}
err := c.Wait()
fmt.Printf("err: %+v\n", err)
}