源文件 博客/上下文/tomb/tomb.go
1 // +build OMIT 2 3 // Package tomb provides a Context implementation that is canceled when either 4 // its parent Context is canceled or a provided Tomb is killed. 5 package tomb 6 7 import ( 8 "golang.org/x/net/context" 9 tomb "gopkg.in/tomb.v2" 10 ) 11 12 // NewContext returns a Context that is canceled either when parent is canceled 13 // or when t is Killed. 14 func NewContext(parent context.Context, t *tomb.Tomb) context.Context { 15 ctx, cancel := context.WithCancel(parent) 16 go func() { 17 select { 18 case <-t.Dying(): 19 cancel() 20 case <-ctx.Done(): 21 } 22 }() 23 return ctx 24 } 25