协程的cancel
close版本
package ch20import ("fmt""testing""time"
)
func isCancelled(cancelChan chan struct{}) bool {select {case <- cancelChan:return truedefault:return false}
}
func cancel_1(cancelChan chan struct{}) {cancelChan <- struct{}{}
}
func cancel_2(cancelChan chan struct{}) {close(cancelChan)
}func TestCancel(t *testing.T) {cancelChan := make(chan struct{},0)for i:=0;i<5;i++{go func(i int,cancelCh chan struct{}) {for{if isCancelled(cancelCh){break}time.Sleep(time.Millisecond *5)}fmt.Println(i,"Cancel")}(i,cancelChan)}cancel_2(cancelChan)time.Sleep(time.Second*1)
}
context 版本
package contextimport ("context""fmt""testing""time"
)
func isCancelled(ctx context.Context) bool {select {case <- ctx.Done():return truedefault:return false}
}func TestCancel(t *testing.T) {ctx,cancel:= context.WithCancel(context.Background())for i:=0;i<5;i++{go func(i int,ctx context.Context) {for{if isCancelled(ctx){break}time.Sleep(time.Millisecond *5)}fmt.Println(i,"Cancel")}(i,ctx)}cancel()time.Sleep(time.Second*1)
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!