Context
- 根context:通过context.background()来创建
- 子context:context.withCancel(parentContext)创建
- ctx,cancel := context.WithCancel(context.Background())
- 当前context被取消时,基于当前context的子context都会被取消
- 接收取消通知:<-ctx.Done()
package cancel
import (
"context"
"fmt"
"testing"
"time"
)
func isCancelled(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
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, "Cancelled")
}(i, ctx)
}
cancel()
time.Sleep(time.Second * 1)
}