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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| package p1
import ( "fmt" "context" "time" )
func ContextCase(){ ctx := context.Background() ctx = context.WithValue(ctx, "desc", "ContextCase") ctx, cancel := context.WithTimeout(ctx, time.Second * 2) defer cancel()
data := [][]int{ {1,2}, {3,4}, } ch := make(chan []int) go calculate(ctx, ch)
for i:=0;i<len(data);i++{ ch <- data[i] } time.Sleep(10*time.Second)
}
func calculate(ctx context.Context, data <- chan []int){ for { select { case item := <- data : ctx := context.WithValue(ctx, "desc", "calculate") ch := make (chan []int) go sumContext(ctx, ch) ch <- item
ch1 := make (chan []int) go muliContext(ctx, ch1) ch1 <- item
case <-ctx.Done(): desc := ctx.Value("desc").(string) fmt.Printf("calculate协程退出,context desc:%s,错误消息:%s\n", desc, ctx.Err()) return } } }
func sumContext(ctx context.Context, data <- chan []int){ for { select { case item := <- data : a,b := item[0], item[1] res := sum(a, b) fmt.Printf("%d + %d = %d\n",a,b,res) case <-ctx.Done(): desc := ctx.Value("desc").(string) fmt.Printf("sumContext协程退出,context desc:%s,错误消息:%s\n", desc, ctx.Err()) return } } }
func muliContext(ctx context.Context, data <- chan []int){ for { select { case item := <- data : a,b := item[0], item[1] res := multi(a, b) fmt.Printf("%d + %d = %d\n",a,b,res) case <-ctx.Done(): desc := ctx.Value("desc").(string) fmt.Printf("muliContext协程退出,context desc:%s,错误消息:%s\n", desc, ctx.Err()) return } } }
func sum(a,b int) int { return a + b } func multi(a, b int) int{ return a * b }
|