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) }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。