mirror of https://github.com/k3s-io/k3s
25 lines
712 B
Go
25 lines
712 B
Go
![]() |
package util
|
||
|
|
||
|
import "context"
|
||
|
|
||
|
// ContextForChannel derives a child context from a parent channel.
|
||
|
//
|
||
|
// The derived context's Done channel is closed when the returned cancel function
|
||
|
// is called or when the parent channel is closed, whichever happens first.
|
||
|
//
|
||
|
// Note the caller must *always* call the CancelFunc, otherwise resources may be leaked.
|
||
|
//
|
||
|
// Backported from https://github.com/kubernetes/apimachinery/blob/v0.25.2/pkg/util/wait/wait.go#L299
|
||
|
func ContextForChannel(parentCh <-chan struct{}) (context.Context, context.CancelFunc) {
|
||
|
ctx, cancel := context.WithCancel(context.Background())
|
||
|
|
||
|
go func() {
|
||
|
select {
|
||
|
case <-parentCh:
|
||
|
cancel()
|
||
|
case <-ctx.Done():
|
||
|
}
|
||
|
}()
|
||
|
return ctx, cancel
|
||
|
}
|