select 有没有 default: ,效果是不一样的
select {
case <-ctx.Done():
println(name, " get message to quit")
}
//等价于
<-ctx.Done()
println(name, " get message to quit")
用例如下:
package main
import (
"context"
"fmt"
"time"
)
func main() {
//3秒后停止go协程
ctx2, _ := context.WithTimeout(context.Background(), time.Second*3)
go work(ctx2, "time cancel")
// 等待子协程运行结束
time.Sleep(time.Second * 4)
}
func work(ctx context.Context, name string) {
for {
//select 用法特别说明
//如果没有 default: 就相当于 中断等待 <-ctx.Done() 收到信号
//如果有default:可以绕过中断 ,继续执行后续代码
select {
case <- ctx.Done():
println(name, " get message to quit")
return
default: // 坑 : 没有default 后续代码无法执行
}
// 有default 后续代码才会执行
// 每次循环休眠一秒
println(name, " is running", time.Now().String())
time.Sleep(time.Second)
}
}
所谓的坑: 就是select 中的 default 写不写对后续代码是有影响的