百度一堆都说的是读超时的示例,,某些场合下需要写超时。这里给出一个写超时的示例。能用代码的就不废话了:
package main
import (
"fmt"
"time"
)
func main() {
work := make(chan bool,1)
// work <- false
timeout := make(chan bool, 1)
go func() {
time.Sleep(time.Second)
timeout <- true
}()
for {
select {
case <-timeout:
fmt.Println("timeout.")
return
case work <- true:
fmt.Println("send...")
}
}
}
保存文件运行go run file.go输出
send...
timeout.
去掉 // work <- false的注释去掉,再次运行输出:
timeout.
case work <- true 表示如果写入成功就执行fmt.Println("send...")。