golang context

Go语言中的Context、Cancel和超时上下文管理

作用:用于在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 WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
	if parent == nil {
		panic("cannot create context from nil parent")
	}
	c := newCancelCtx(parent)
	propagateCancel(parent, &c)
	return &c, func() { c.cancel(true, Canceled) }
}

// newCancelCtx returns an initialized cancelCtx.
func newCancelCtx(parent Context) cancelCtx {
	return cancelCtx{Context: parent}
}

func propagateCancel(parent Context, child canceler) {
	fmt.Println("propagateCancel")
	done := parent.Done()
	if done == nil {
		return // parent is never canceled
	}

	select {
	case <-done:
		// parent is already canceled
		child.cancel(false, parent.Err())
		return
	default:
	}

	if p, ok := parentCancelCtx(parent); ok {
		p.mu.Lock()
		if p.err != nil {
			// parent has already been canceled
			child.cancel(false, p.err)
		} else {
			if p.children == nil {
				p.children = make(map[canceler]struct{})
			}
			// 保存子ctx
			p.children[child] = struct{}{}
		}
		p.mu.Unlock()
	} else {
		atomic.AddInt32(&goroutines, +1)
		go func() {
			select {
			case <-parent.Done():
				child.cancel(false, parent.Err())
			case <-child.Done():
			}
		}()
	}
}


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) // 关闭channel, 用于通知ctx.Done()
	}

	// 关闭所有子ctx
	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)
	}
}

timeout ctx

在cancelctx的基础上实现,只是多了个定时器自动调用cancel

type timerCtx struct {
	cancelCtx
	timer *time.Timer // Under cancelCtx.mu.

	deadline time.Time
}

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
	if parent == nil {
		panic("cannot create context from nil parent")
	}
	if cur, ok := parent.Deadline(); ok && cur.Before(d) {
		// The current deadline is already sooner than the new one.
		return WithCancel(parent)
	}
	c := &timerCtx{
		cancelCtx: newCancelCtx(parent),
		deadline:  d,
	}
	propagateCancel(parent, c)
	dur := time.Until(d)
	if dur <= 0 {
		c.cancel(true, DeadlineExceeded) // deadline has already passed
		return c, func() { c.cancel(false, Canceled) }
	}
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.err == nil {
		c.timer = time.AfterFunc(dur, func() {
			c.cancel(true, DeadlineExceeded)
		})
	}
	return c, func() { c.cancel(true, Canceled) }
}

value ctx

type valueCtx struct {
	Context
	key, val interface{}
}
func WithValue(parent Context, key, val interface{}) Context {
	if parent == nil {
		panic("cannot create context from nil parent")
	}
	if key == nil {
		panic("nil key")
	}
	//	if !reflectlite.TypeOf(key).Comparable() {
	//	panic("key is not comparable")
	//}
	return &valueCtx{parent, key, val}
}
func (c *valueCtx) Value(key interface{}) interface{} {
	if c.key == key {
		return c.val
	}
	return c.Context.Value(key)
}

### GolangContext 的使用教程 #### 创建和传递 `context.Context` `Context` 是 Go 语言中用于在 goroutine 之间传递请求范围的数据、取消信号和其他内容的标准方式。创建一个新的上下文通常通过调用 `context.Background()` 或者 `context.TODO()` 来实现[^1]。 当需要向现有上下文中添加截止时间、超时或者键值对的时候,可以利用如下函数: - `WithCancel`: 返回带有取消功能的新子上下文; - `WithValue`: 向父级上下文中加入键值对; - `WithDeadline`: 设置绝对结束期限; - `WithTimeout`: 基于当前时间设置相对过期时间; ```go ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() ``` 上述代码片段展示了如何基于背景上下文创建一个具有五秒超时期限的新上下文实例,并立即安排其释放资源的操作[^2]。 #### 取消操作与监听取消事件 为了能够响应取消指令,在启动新的 Goroutines 执行任务之前应该总是先获取到对应的上下文对象以及它的取消方法。一旦不再需要该协程继续运行,则应尽早调用此取消回调来通知其他依赖于此上下文的任务停止工作并清理现场[^3]。 ```go select { case <-time.After(1 * time.Minute): fmt.Println("Operation completed.") case <-ctx.Done(): fmt.Printf("Operation was cancelled or timed out: %v\n", ctx.Err()) } ``` 这段程序会等待一分钟完成某项耗时较长的工作,但如果在此之前关联的上下文被标记为已完成(无论是因为达到了设定的时间限制还是显式地触发了取消),它就会提前退出循环体执行后续逻辑处理[^4]。 #### 错误处理模式 对于由 `Done()` 方法返回通道所携带的信息而言,一般情况下只会有三种可能的结果——正常关闭、由于超时而终止或者是收到外部发出的手动取消命令。因此可以通过检查错误的具体类型来进行相应的异常恢复措施[^5]。 ```go if err != nil && errors.Is(err, context.Canceled) { log.Fatal("Request canceled by the user") } else if err != nil && errors.Is(err, context.DeadlineExceeded){ log.Fatal("Request processing took too long and has been terminated") } ``` 以上示例演示了怎样区分不同类型的取消原因以便采取恰当的动作回应这些状况的发生[^6]。 #### 实际应用场景举例 考虑这样一个场景:构建 RESTful API 接口服务端应用时经常遇到并发请求的情况,此时就可以借助 `net/http` 包内置的支持机制自动将 HTTP 请求映射成合适的上下文结构供内部业务层组件消费使用[^7]。 ```go func handler(w http.ResponseWriter, r *http.Request) { // Extract context from incoming request. ctx := r.Context() select { case <-time.After(time.Duration(rand.Intn(5)) * time.Second): w.WriteHeader(http.StatusOK) _, _ = io.WriteString(w, "Hello!\n") case <-ctx.Done(): w.WriteHeader(http.StatusServiceUnavailable) _, _ = io.WriteString(w, "Sorry, can't serve your request now.\n") } } ``` 这里定义了一个简单的HTTP处理器函数,它会在随机延迟一段时间之后给客户端发送问候消息,不过如果期间收到了来自上游服务器转发过来的中断指示则改为告知对方暂时无法提供服务[^8]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值