Go Wiki: 超时与截止时间
要放弃运行过长的同步调用,请使用带 time.After 的 select 语句
import "time"
c := make(chan error, 1)
go func() { c <- client.Call("Service.Method", args, &reply) } ()
select {
case err := <-c:
// use err and reply
case <-time.After(timeoutNanoseconds):
// call timed out
}
请注意,通道 c
的缓冲区大小为 1。如果它是一个无缓冲通道,并且 client.Call 方法的执行时间超过 timeoutNanoseconds
,那么通道发送将会永远阻塞,goroutine 也将永远不会被销毁。
参考
time.After: https://pkg.go.dev/time/#After
select: https://go-lang.org.cn/ref/spec#Select_statements
博客文章: https://go-lang.org.cn/blog/2010/09/go-concurrency-patterns-timing-out-and.html
此内容是 Go Wiki 的一部分。