package main import ( "context" "fmt" "time" ) var ( cxt context.Context cxt1 context.Context cancelFunction context.CancelFunc ) func gooo(ctx context.Context,num int){ for{ select{ case <-ctx.Done() : fmt.Println("退出操作",num) return default: fmt.Println("默认操作.........",num) time.Sleep(time.Second*2) } } } func main() { cxt = context.Background() cxt,cancelFunction = context.WithCancel(cxt) cxt1,cancelFunct := context.WithCancel(cxt) go gooo(cxt,1) go gooo(cxt1,2) // cancelFunction = cancelFunction time.Sleep(time.Second*10) cancelFunct() time.Sleep(time.Second * 10) cancelFunction() fmt.Println("exited....") }
package main import ( "context" "fmt" "time" ) var ( cxt context.Context cxt1 context.Context cancelFunction context.CancelFunc ) func gooo(ctx context.Context,_ := context.WithCancel(cxt) go gooo(cxt,2) // cancelFunction = cancelFunction time.Sleep(time.Second * 10) cancelFunction() fmt.Println("exited....") time.Sleep(time.Second*300) }