【Golang】源码学习:contex包——从功能到源码理解Go Context机制(二)

第一部分链接:https://blog.csdn.net/qq_38093301/article/details/104370248

三、源码学习

Context包高度提炼了功能边界,对外只暴露统一的Context接口,最大程度的隐藏的实现细节,对于接口的设计非常简洁。

Context接口的定义如下:

type Context interface {
    Deadline() (deadline time.Time, ok bool)
    Done() <-chan struct{}
    Err() error
    Value(key interface{}) interface{}
}

这四个函数对外提供的功能不再赘述,在context包中,共有四个类型实现了该接口:

emptyCtx:默认初始的context使用的类型,仅实现Context接口,不做任何处理,返回默认空值。

valueCtx:对应携带K-V值的context接口实现,携带k-v数据成员,实现了value函数的具体操作。

cancelCtx:实现了cancler接口,为context提供了可取消自身和子孙的功能。

timerCtx:在cancelCtx的基础上,对带有定时功能的Context进行了实现。

1、emptyCtx:即空context,也是所有子context的祖先

emptyCtx的定义非常简单,但是整个Context包中最精彩的设计之一:

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"
}

可以看到,emptyCtx仅对int类型做了新的类型定义,然后实现了Context接口,各函数不做任何操作,仅仅返回默认值。

这个实现只用于在包内定义两个内部实例,并提供对外访问函数。

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

func Background() Context {
	return background
}
func TODO() Context {
	return todo
}

在外部使用context.Background()和context.Backgroun

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值