🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
Context与任务的取消 === 一个任务有起了多个子任务 ![](https://box.kancloud.cn/ebd80a55a0f8ea09ea9213126a392969_1031x306.png) - 根Context: 通过context.Background() 创建 - 子`Context context.WithCancel(父context)`创建 - `ctx, cancel := context.WithCancel(context.Background())` - 当前Context被取消时,基于他的子context都会被取消 - 接受取消通知`<-ctx.Done()` ~~~ func TestService(t *testing.T) { dataCh := make(chan int,10) end := make(chan bool) ctx, cancel := context.WithCancel(context.Background()) go production(dataCh,cancel) go consume(ctx,dataCh,end) <-end } // 生产者 func production(ch chan int,cancelFunc context.CancelFunc) { for i:=0;i<1000;i++{ ch<-i } cancelFunc() } // 消费者 func consume(ctx context.Context,ch chan int,end chan bool) { forloop: for { select { case data := <-ch: fmt.Println(data) case <-ctx.Done(): fmt.Println("end------------------") break forloop } } end<-true } ~~~ 这个例子没有举好,大家先知道怎么用