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.dev.org.tw/ref/spec#Select_statements
部落格文章:https://go.dev.org.tw/blog/2010/09/go-concurrency-patterns-timing-out-and.html
此內容是 Go Wiki 的一部分。