Go面试简单笔记2

context的结构原理

  1. 为什么需要context
    需求:上层任务取消后,其下层任务全部取消,并不影响上层任务和同级任务
  2. context是什么
    context的接口
type Context interface {

    Deadline() (deadline time.Time, ok bool) //返回截止时间
 
    Done() <-chan struct{} // 当前任务被取消时,返回一个关闭的channel,否则返回nil

    Err() error

    Value(key interface{}) interface{} // 返回context存储的键值对中当前key对应的值
}
  1. 几种ctx
  2. emptyCtx,一个int变量,实现了Contex接口,没有deadline,一般用来作为context树的根节点
type emptyCtx int
  1. valueCtx
    Context变量继承父节点所有信息,并且有key,value键值对,可以携带额外信息,如果当前找不到对应的key,会沿着Context往上找key对应的值,调用WithValue创建子节点并添加到当前的context链中
type valueCtx struct {
    Context
    key, val interface{}
}
  1. CancelCtx
    一个Context作为父节点,变量done表示一个channel用来传递关闭信号;children是一个map,存储子节点;有一个cancel方法关闭当前和其子节点的context并且设置取消原因
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
}
  1. timerCtx
    基于cancelctx的类型,可以定时取消
type timerCtx struct {
    cancelCtx
    timer *time.Timer // Under cancelCtx.mu.

    deadline time.Time
}

使用Context的好处

在gin框架中,请求处理函数都会传入context,在处理流程中使用一个context链贯穿server,connection,request,可以将上游的信息共享,也可以通过取消上游来取消下游任务,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值