ARTICLE AD BOX
Lets say I wanted to create a context which gets cancelled as soon as all of some subcontexts got cancelled. Would this be a valid way to do that, or is there a better option? My idea is, that the last subcontext that gets cancelled can not send to the cancelCounter since the buffer is full, so it goes to the default case and cancels ctx.
var subcontexts []context.Context = ... ctx, cancel := context.WithCancel(context.Background()) defer cancel() cancelCounter := make(chan struct{}, len(subcontexts)-1) for _, c := range subcontexts { stop := context.AfterFunc(c, func() { select { case cancelCounter <- struct{}{}: default: cancel() } }) defer stop() } // do something with ctx that gets cancelled // when all subcontexts got cancelled