【go】context作用以及源码分析

context是什么?

context是在go中在goroutine之间传递特定值,取消信号和截止时间的机制

context 接口定义 :

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}
}
  1. Deadline方法用于获取Context的截止时间,如果没有设置截止时间则返回false。
  2. Done方法用于获取一个只读的channel,当Context被取消或者到达截止时间时,该channel会被关闭。
  3. Err方法用于获取Context的错误信息,如果Context未被取消则返回nil。
  4. Value方法用于获取Context中指定键的值,如果键不存在则返回nil。

context实现类型

Context接口的实现主要有两种类型:cancelCtx和timerCtx

cancelCtx

type cancelCtx struct {
    Context // 嵌入Context接口
    mu sync.Mutex // Mutex锁,用于保证并发安全性
    done chan struct{} // 一个只读的channel,用于通知Context已经被取消
    err error // Context的错误信息
}

timerCtx

type timerCtx struct {
    cancelCtx // 嵌入cancelCtx结构体
    deadline time.Time // 截止时间
    timer *time.Timer // 定时器
}

Context的创建

通过WithCancel、WithDeadline、WithTimeout和WithValue等函数创建。这些函数会返回一个新的Context和一个取消函数,可以用于取消Context的操作

WithCancel函数

WithCancel函数用于创建一个基础的Context实现,它包含了一个父级Context、一个取消函数cancel和一个只读的channel done。当使用cancel函数,会关闭done channel并且停止所有goroutine运行

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
    c := newCancelCtx(parent)
    propagateCancel(parent, &c)
    return &c, func() { c.cancel(true, Canceled) }
}

WithDeadline函数

WithDeadline函数和WithTimeout函数用于创建一个带有截止时间的Context实现。当到达截止时间时,会自动取消Context,并关闭done channel。

func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) {
    c := &timerCtx{
        cancelCtx: newCancelCtx(parent),
        deadline:  deadline,
    }
    propagateCancel(parent, c)
    d := c.deadline.Sub(time.Now())
    if d <= 0 {
        c.cancel(true, DeadlineExceeded)
        return c, func() { c.cancel(true, Canceled) }
    }
    c.timer = time.AfterFunc(d, func() {
        c.cancel(true, DeadlineExceeded)
    })
    return c, func() { c.cancel(true, Canceled) }
}

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

WithValue函数

用于创建一个包含指定键值对的Context实现。这些键值对可以在多个goroutine之间传递信息。

func WithValue(parent Context, key, val interface{}) Context {
    if key == nil {
        panic("nil key")
    }
    if val == nil {
        panic("nil value")
    }
    return &valueCtx{parent, key, val}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Context包是Go语言内置的一个标准库,主要用于多个Goroutine之间的上下文传递和控制。它提供了一种机制来传递取消信号、截止时间和一些其他的请求/值,这些请求/值可以跨越多个API边界和Goroutine传递,而不需要显式地传递。 以下是Context包的主要源码分析: 1. Context接口 Context接口定义了一个可取消的上下文,它包括了Deadline截止时间、Done通道和Value键值对数据。 ```go type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key interface{}) interface{} } ``` 2. context.Background() Background函数返回一个空的Context,它没有任何值和截止时间,而且永远不会取消。它被广泛用于Main函数、初始化和测试中。 ```go func Background() Context { return background } var ( background = new(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 } ``` 3. context.TODO() TODO函数返回一个非空的Context,它没有任何值和截止时间,而且永远不会取消。它被广泛用于暂时不确定上下文应该是什么的情况。 ```go func TODO() Context { return todo } var ( todo = new(emptyCtx) ) ``` 4. context.WithCancel() WithCancel函数返回一个带有CancelFunc的Context,当CancelFunc调用时,Context的Done通道将被关闭。这个函数可以用来取消长时间运行的操作。 ```go func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { c := newCancelCtx(parent) propagateCancel(parent, &c) return &c, func() { c.cancel(true, Canceled) } } 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 newCancelCtx(parent Context) cancelCtx { return cancelCtx{Context: parent} } 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() defer c.mu.Unlock() return c.err } 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) } } type canceler interface { cancel(removeFromParent bool, err error) } var closedchan = make(chan struct{}) func init() { close(closedchan) } ``` 5. context.WithDeadline() WithDeadline函数返回一个带有截止时间的Context,当截止时间到达或者调用CancelFunc时,Context的Done通道将被关闭。 ```go func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return WithCancel(parent) } c := &timerCtx{ cancelCtx: newCancelCtx(parent), deadline: deadline, } propagateCancel(parent, c) d := c.deadline.Sub(time.Now()) if d <= 0 { c.cancel(true, DeadlineExceeded) // deadline has already passed return c, func() { c.cancel(true, Canceled) } } c.mu.Lock() defer c.mu.Unlock() if c.err == nil { c.timer = time.AfterFunc(d, func() { c.cancel(true, DeadlineExceeded) }) } return c, func() { c.cancel(true, Canceled) } } type timerCtx struct { cancelCtx deadline time.Time mu sync.Mutex // protects timer and err timer *time.Timer err error } func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { return c.deadline, true } func (c *timerCtx) cancel(removeFromParent bool, err error) { c.cancelCtx.cancel(false, err) // propagate the cancel first c.mu.Lock() if c.timer != nil { c.timer.Stop() c.timer = nil } c.err = err c.mu.Unlock() if removeFromParent { removeChild(c.cancelCtx.Context, c) } } ``` 6. context.WithTimeout() WithTimeout函数返回一个带有超时时间的Context,当超时时间到达或者调用CancelFunc时,Context的Done通道将被关闭。 ```go func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { return WithDeadline(parent, time.Now().Add(timeout)) } ``` 7. context.WithValue() WithValue函数返回一个带有键值对数据的Context,这个数据可以跨越多个API边界和Goroutine传递,而不需要显式地传递。 ```go func WithValue(parent Context, key, val interface{}) Context { if key == nil { panic("nil key") } if val == nil { panic("nil value") } return &valueCtx{parent, key, val} } type valueCtx struct { Context key, val interface{} } func (c *valueCtx) Value(key interface{}) interface{} { if c.key == key { return c.val } return c.Context.Value(key) } ``` 以上就是Context包的源码分析Context包提供了一种简单而强大的机制来传递请求/值和取消信号,可以用于管理并发访问、超时控制和错误处理等场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值