结构体

type Context interface {
    // 标识deadline是否已经设置了,没有设置时,ok的值是false,并返回初始的time.Time
    Deadline() (deadline time.Time, ok bool)
    // 返回一个channel, 当返回关闭的channel时可以执行一些操作
    Done() <-chan struct{}
    // 描述context关闭的原因,通常在Done()收到关闭通知之后才能知道原因
    Err() error
    // 获取上游Goroutine 传递给下游Goroutine的某些数据
    Value(key interface{}) interface{}
}

emptyCtx

type emptyCtx int

func (*emptyCtx) Deadline() (deadline time.Time, ok bool) {
    return
}

func (*emptyCtx) Done() <-chan struct{} {
    return nil
}

func (*emptyCtx) Err() error {
    return nil
}

func (*emptyCtx) Value(key interface{}) interface{} {
    return nil
}

func (e *emptyCtx) String() string {
    switch e {
    case background:
        return "context.Background"
    case todo:
        return "context.TODO"
    }
    return "unknown empty Context"
}

var (
    background = new(emptyCtx)
    todo       = new(emptyCtx)
)

func Background() Context {
    return background
}

func TODO() Context {
    return todo
}

cancelCtx

// A cancelCtx can be canceled. When canceled, it also cancels any children
// that implement canceler.
type cancelCtx struct {
    Context

    mu       sync.Mutex            // protects following fields
    done     chan struct{}         // created lazily, closed by first cancel call
    children map[canceler]struct{} // set to nil by the first cancel call
    err      error                 // set to non-nil by the first cancel call
}

func (c *cancelCtx) Done() <-chan struct{} {
    c.mu.Lock()
    if c.done == nil {
        c.done = make(chan struct{})
    }
    d := c.done
    c.mu.Unlock()
    return d
}

func (c *cancelCtx) Err() error {
    c.mu.Lock()
    err := c.err
    c.mu.Unlock()
    return err
}

func (c *cancelCtx) String() string {
    return fmt.Sprintf("%v.WithCancel", c.Context)
}

// cancel closes c.done, cancels each of c's children, and, if
// removeFromParent is true, removes c from its parent's children.
func (c *cancelCtx) cancel(removeFromParent bool, err error) {
    if err == nil {
        panic("context: internal error: missing cancel error")
    }
    c.mu.Lock()
    if c.err != nil {
        c.mu.Unlock()
        return // already canceled
    }
    c.err = err
    if c.done == nil {
        c.done = closedchan
    } else {
        close(c.done)
    }
    for child := range c.children {
        // NOTE: acquiring the child's lock while holding parent's lock.
        child.cancel(false, err)
    }
    c.children = nil
    c.mu.Unlock()

    if removeFromParent {
        removeChild(c.Context, c)
    }
}

valueCtx

type valueCtx struct {
    Context
    key, val interface{}
}

func (c *valueCtx) String() string {
    return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val)
}

func (c *valueCtx) Value(key interface{}) interface{} {
    if c.key == key {
        return c.val
    }
    return c.Context.Value(key)
}

timerCtx

type timerCtx struct {
    cancelCtx
    timer *time.Timer // Under cancelCtx.mu.

    deadline time.Time
}

func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
    return c.deadline, true
}

func (c *timerCtx) String() string {
    return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, time.Until(c.deadline))
}

func (c *timerCtx) cancel(removeFromParent bool, err error) {
    c.cancelCtx.cancel(false, err)
    if removeFromParent {
        // Remove this timerCtx from its parent cancelCtx's children.
        removeChild(c.cancelCtx.Context, c)
    }
    c.mu.Lock()
    if c.timer != nil {
        c.timer.Stop()
        c.timer = nil
    }
    c.mu.Unlock()
}

WithCancel

// newCancelCtx returns an initialized cancelCtx.
func newCancelCtx(parent Context) cancelCtx {
    return cancelCtx{Context: parent}
}
func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
    // 创建cancelCtx实例
    c := newCancelCtx(parent)
    // 添加到父节点的children中
    propagateCancel(parent, &c)
    // 返回实例和方法
    return &c, func() { c.cancel(true, Canceled) }
}

使用示例

package main

import (
    "context"
    "fmt"
    "time"
)

func MyOperate1(ctx context.Context) {
    for {
        select {
        default:
            fmt.Println("MyOperate1", time.Now().Format("2006-01-02 15:04:05"))
            time.Sleep(2 * time.Second)
        case <-ctx.Done():
            fmt.Println("MyOperate1 Done")
            return
        }
    }
}
func MyOperate2(ctx context.Context) {
    fmt.Println("Myoperate2")
}
func MyDo2(ctx context.Context) {
    go MyOperate1(ctx)
    go MyOperate2(ctx)
    for {
        select {
        default:
            fmt.Println("MyDo2 : ", time.Now().Format("2006-01-02 15:04:05"))
            time.Sleep(2 * time.Second)
        case <-ctx.Done():
            fmt.Println("MyDo2 Done")
            return
        }
    }

}
func MyDo1(ctx context.Context) {
    go MyDo2(ctx)
    for {
        select {
        case <-ctx.Done():
            fmt.Println("MyDo1 Done")
            // 打印 ctx 关闭原因
            fmt.Println(ctx.Err())
            return
        default:
            fmt.Println("MyDo1 : ", time.Now().Format("2006-01-02 15:04:05"))
            time.Sleep(2 * time.Second)
        }
    }
}
func main() {
    // 创建 cancelCtx 实例
    // 传入context.Background() 作为根节点
    ctx, cancel := context.WithCancel(context.Background())
    // 向协程中传递ctx
    go MyDo1(ctx)
    time.Sleep(5 * time.Second)
    fmt.Println("stop all goroutines")
    // 执行cancel操作
    cancel()
    time.Sleep(2 * time.Second)
}

WithDeadline 表示context在指定的时刻结束


func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
    if cur, ok := parent.Deadline(); ok && cur.Before(d) {
        // The current deadline is already sooner than the new one.
        return WithCancel(parent)
    }
    c := &timerCtx{
        cancelCtx: newCancelCtx(parent),
        deadline:  d,
    }
    propagateCancel(parent, c)
    dur := time.Until(d)
    if dur <= 0 {
        c.cancel(true, DeadlineExceeded) // deadline has already passed
        return c, func() { c.cancel(false, Canceled) }
    }
    c.mu.Lock()
    defer c.mu.Unlock()
    if c.err == nil {
        c.timer = time.AfterFunc(dur, func() {
            c.cancel(true, DeadlineExceeded)
        })
    }
    return c, func() { c.cancel(true, Canceled) }
}

使用示例

package main

import (
    "context"
    "fmt"
    "time"
)

func dl2(ctx context.Context) {
    n := 1
    for {
        select {
        case <-ctx.Done():
            fmt.Println(ctx.Err())
            return
        default:
            fmt.Println("dl2 : ", n)
            n++
            time.Sleep(time.Second)
        }
    }
}

func dl1(ctx context.Context) {
    n := 1
    for {
        select {
        case <-ctx.Done():
            fmt.Println(ctx.Err())
            return
        default:
            fmt.Println("dl1 : ", n)
            n++
            time.Sleep(2 * time.Second)
        }
    }
}
func main() {
    // 设置deadline为当前时间之后的5秒那个时刻
    d := time.Now().Add(5 * time.Second)
    ctx, cancel := context.WithDeadline(context.Background(), d)
    defer cancel()
    go dl1(ctx)
    go dl2(ctx)
    for{
        select {
            case <-ctx.Done():
                fmt.Println("over",ctx.Err())
                return
        }
    }
}

WithTimeout 实际调用了WithDeadline()


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

使用示例 :

package main

import (
   "context"
   "fmt"
   "time"
)

func to1(ctx context.Context) {
   n := 1
   for {
       select {
       case <-ctx.Done():
           fmt.Println("to1 is over")
           return
       default:
           fmt.Println("to1 : ", n)
           n++
           time.Sleep(time.Second)
       }
   }
}
func main() {
   // 设置为6秒后context结束
   ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
   defer cancel()
   go to1(ctx)
   n := 1
   for {
       select {
       case <-time.Tick(2 * time.Second):
           if n == 9 {
               return
           }
           fmt.Println("number :", n)
           n++
       }
   }
}

WithValue Context 基础上添加了 key : value 的键值对

context 形成的树状结构,后面的节点可以访问前面节点传导的数据

func WithValue(parent Context, key, val interface{}) Context {
   if key == nil {
       panic("nil key")
   }
   if !reflect.TypeOf(key).Comparable() {
       panic("key is not comparable")
   }
   return &valueCtx{parent, key, val}
}

// A valueCtx carries a key-value pair. It implements Value for that key and
// delegates all other calls to the embedded Context.
type valueCtx struct {
   Context
   key, val interface{}
}

使用示例 :

package main

import (
   "context"
   "fmt"
   "time"
)

func v3(ctx context.Context) {
   for {
       select {
       case <-ctx.Done():
           fmt.Println("v3 Done : ", ctx.Err())
           return
       default:
           fmt.Println(ctx.Value("key"))
           time.Sleep(3 * time.Second)
       }
   }
}
func v2(ctx context.Context) {
   fmt.Println(ctx.Value("key"))
   fmt.Println(ctx.Value("v1"))
   // 相同键,值覆盖
   ctx = context.WithValue(ctx, "key", "modify from v2")
   go v3(ctx)
}
func v1(ctx context.Context) {
   if v := ctx.Value("key"); v != nil {
       fmt.Println("key = ", v)
   }
   ctx = context.WithValue(ctx, "v1", "value of v1 func")
   go v2(ctx)
   for {
       select {
       default:
           fmt.Println("print v1")
           time.Sleep(time.Second * 2)
       case <-ctx.Done():
           fmt.Println("v1 Done : ", ctx.Err())
           return
       }
   }
}
func main() {
   ctx, cancel := context.WithCancel(context.Background())
   // 向context中传递值
   ctx = context.WithValue(ctx, "key", "main")
   go v1(ctx)
   time.Sleep(10 * time.Second)
   cancel()
   time.Sleep(3 * time.Second)
}

朝阳
1 声望0 粉丝

« 上一篇
初识actix