1. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
    2. return WithDeadline(parent, time.Now().Add(timeout))
    3. }

    查看代码,WithTimeout其实就是调用了WithDeadline

    1. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
    2. //1. 判断传入的Context是否为空
    3. if parent == nil {
    4. panic("cannot create context from nil parent")
    5. }
    6. //2.
    7. if cur, ok := parent.Deadline(); ok && cur.Before(d) {
    8. // The current deadline is already sooner than the new one.
    9. return WithCancel(parent)
    10. }
    11. c := &timerCtx{
    12. cancelCtx: newCancelCtx(parent),
    13. deadline: d,
    14. }
    15. propagateCancel(parent, c)
    16. dur := time.Until(d)
    17. if dur <= 0 {
    18. c.cancel(true, DeadlineExceeded) // deadline has already passed
    19. return c, func() { c.cancel(false, Canceled) }
    20. }
    21. c.mu.Lock()
    22. defer c.mu.Unlock()
    23. if c.err == nil {
    24. c.timer = time.AfterFunc(dur, func() {
    25. c.cancel(true, DeadlineExceeded)
    26. })
    27. }
    28. return c, func() { c.cancel(true, Canceled) }
    29. }

    WithDeadline
    // 1.判断父context是否已经超时

    // 2.创建一个timerCtx

    // 3. 传播 timerCtx到所有子Context

    // 4.判断距离deadline还剩多少时间

    // 5.