golang Context

Golang 的 context Package 提供了一种简洁又强大方式来管理 goroutine 的生命周期,同时提供了一种 Requst-Scope K-V Store。

当一个计算任务被goroutine承接了之后,由于某种原因(超时,或者强制退出)我们希望中止这个goroutine的计算任务,那么就用得到这个Context了。

context 基本结构:

Context interface

Context interface 是最基本的接口

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}
}
  • Deadline()返回一个time.Time,是当前 Context 的应该结束的时间,ok 表示是否有 deadline
  • Done()返回一个struct{}类型的只读 channel
  • Err()返回 Context 被取消时的错误
  • Value(key interface{}) 是 Context 自带的 K-V 存储功能

canceler interface

canceler interface 定义了提供 cancel 函数的 context,当然要求数据结构要同时实现 Context interface

Structs

除了以上两个 interface 之外,context 包中还定义了若干个struct,来实现上面的 interface

  • emptyCtx
  • cancelCtx
  • timerCtx
  • valueCtx

 

Context派生以及使用例子:https://studygolang.com/articles/9624

posted @ 2021-08-19 15:35  会飞的猿  阅读(84)  评论(0编辑  收藏  举报