LoginSignup
0
2

More than 5 years have passed since last update.

[golang] contextを継承したとき、親contextによる終了か子contextによる終了かを判定する

Posted at

プログラム全体にタイムアウトを設定していて、また特定の関数にもタイムアウトを設定しているとき、どちらによるタイムアウトかを判定したい場合がある。
子contextのDone()closeされたとき、親contextのDone()closeされたかどうかをチェックするとよい。

func main() {
    // 親のcontext
    ctxP, cancelP := context.WithTimeout(context.Background(), 5*time.Second)
RETRY:
    // 子のcontext
    ctxC, cancelC := context.WithTimeout(ctxP, time.Second)
    select {
    case <-ctxC.Done():
        cancelC()
        select {
        // 親のタイムアウト(終了)
        case <-ctxP.Done():
            cancelP()
            fmt.Println("deadline of parent")
        // 子のタイムアウト(リトライ)
        default:
            fmt.Println("deadline of child")
            goto RETRY
        }
    }
}

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2