Go Wiki: タイムアウトとデッドライン
実行時間が長すぎる同期呼び出しを破棄するには、select ステートメントを time.After と一緒に使用します。
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 よりも長くかかった場合、チャネルの送信は永遠にブロックされ、ゴルーチンは決して破棄されません。
参考文献
time.After: https://pkg.go.dev/time/#After
select: https://go.dokyumento.jp/ref/spec#Select_statements
ブログ記事: https://go.dokyumento.jp/blog/2010/09/go-concurrency-patterns-timing-out-and.html
このコンテンツはGo Wikiの一部です。