golang context

作用:用于在go协程中 传递上下文、超时、取消、传值

底层实现:是由互斥锁、channel、map来实现的
互斥锁:保护临界资源
channel: 用于信号通知,比如ctx.Done()
map: 保存父ctx下派生的所有子ctx, 父ctx关闭,子ctx都关闭

实现的接口

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

空ctx

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
}

cancel ctx

使用map保存所有子ctx,确保父ctx cancel后,子ctx也cancel

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值