func main() {
cxt,cancel := context.WithCancel(context.Background())
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-cxt.Done():
time.Sleep(time.Second)
fmt.Println("it cancel")
break
//只会跳出select 不会跳出for循环
//在这里能够间接return
//或者配合label标签推出循环
default:
fmt.Println("Go go go")
time.Sleep(time.Second)
}
}
}()
time.Sleep(1500*time.Millisecond)
cancel()
wg.Wait()
}
Go go go
Go go go
it cancel
it cancel
it cancel
it cancel
it cancel
···
//死循环