context 作用
context用来解决goroutine 之间传递上下文信息,包括:取消信号、超时时间、截止时间、k-v 等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
package main
import ( "context" "fmt" "time" )
func main() { ctx, cel := context.WithCancel(context.Background())
go pushDockerToHarbor(ctx) go pushImageToMinio(ctx)
time.Sleep(6 * time.Second) cel()
time.Sleep(5 * time.Second) }
func pushImageToMinio(ctx context.Context) { go func() { fmt.Println("i doing push image to minio worker") time.Sleep(5 * time.Second) }()
for { select { case <-ctx.Done(): fmt.Println("canceled") return case <-time.After(30 * time.Minute): fmt.Println("timeout") return } } }
func pushDockerToHarbor(ctx context.Context) { go func() { fmt.Println("i doing push docker to harbor worker") time.Sleep(5 * time.Second) }()
for { select { case <-ctx.Done(): fmt.Println("canceled") return case <-time.After(30 * time.Minute): fmt.Println("timeout") return } } }
|
参考文档