企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## context Context 1. 根Context: context.Background()创建; 2. 子Context: context.WithCancel(parentContext)创建; ctx, cancel := context.WithCancel(context.Background()) 3. 当前Context被取消时,基于它的子Context都会被取消; 4. 接收取消通知:<- ctx.Done() ~~~ func isCancel(ctx context.Context) bool { select { case <-ctx.Done(): return true default: return false } } func TestContextTaskCancel(t *testing.T) { cxt, cancel := context.WithCancel(context.Background()) for i := 1; i <= 5; i++ { go func(no int, ctx context.Context) { for { if isCancel(ctx) { fmt.Printf("task %v is canceled \n", no) return } fmt.Println("task is running=>", time.Now()) time.Sleep(time.Millisecond * 500) } }(i, cxt) } time.Sleep(2 * time.Second) cancel() time.Sleep(1 * time.Second) fmt.Println("main goroutine end") } ~~~