go协程控制——context

context

为什么有context

  1. 首先,如果我们在并发程序中,如果需要我们去通知子协程结束我们会怎么做?

  2. 我们可能会通过一个channel+select去通知,如下:

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main()  {
    	exitChan := make(chan bool)
    
    	go func() {
    		for {
    			fmt.Println("Doing Work......")
    			select {
    				case <-exitChan:
    					return
    			}
    		}
    	}()
    
    	time.Sleep(time.Second * 1)
    	fmt.Println("stop the goRoutinue")
    	close(exitChan)
    	time.Sleep(time.Second * 3)
    }
    
  3. 这种做法能传递我们需要给子协程的信号,但是他是有限的,比如如果我想在指定的时间间隔内通知,想传递为什么取消的信息,如果需要控制子协程以及子协程的子协程,多个层级下使用exit Channel的方式会变得混乱复杂,所以官方就为goroutine控制开发了context包

什么是context

  1. context是协程并发安全的

  2. context包可以从已有的context实例派生新的context,形成context的树状结构,只要一个context取消了,派生出来的context将都会被取消

创建context树:

  1. 第一步创建根结点, 使用emptyCtx(int类型变量)…context.Background经常用做context树的根结点,由接收请求的第一个routine创建,不能被取消,没有值也没有过期时间

    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
    }
    // emptyCtx不能存储额外信息,没有超时时间,不能取消,都是nil
    
    // Background returns a non-nil, empty Context. It is never canceled, has no
    // values, and has no deadline. It is typically used by the main function,
    // initialization, and tests, and as the top-level Context for incoming
    // requests.
    func Background() Context {
     return background
    }
    
    // TODO returns a non-nil, empty Context. Code should use context.TODO when
    // it's unclear which Context to use or it is not yet available (because the
    // surrounding function has not yet been extended to accept a Context
    // parameter).
    func TODO() Context {
     return todo
    }
    

    通过注释,可以看到context.Background返回一个非空的context,通常由主函数,初始化和测试使用,并作为传入请求的top-level Context (顶级上下文)。TODO也是返回一个非空的context,当不知道应该使用context时使用TODO…两者只是使用场景不同,代码实现都是一样

  2. 创建子孙节点由四个函数

    • func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
      // 对应cancelCtx(参考文末的structure图)
      // 返回ctx和cancel函数,可以让后代的goroutine退出,关闭对应的c.done
      // 创建了可取消的cancelCtx类型 =》 对应下面的cancelCtx
      func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
      	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}
    }
    
    // propagateCancel arranges for child to be canceled when parent is.
    func propagateCancel(parent Context, child canceler) {
    	if parent.Done() == nil {
    		return // parent is never canceled
    	}
      // 获取cancelCtx
    	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{})
    			}
    			p.children[child] = struct{}{}
    		}
    		p.mu.Unlock()
    	} else {
    		go func() {
          // 监听父节点,返回的channel如果关闭,当前的context也取消了
    			select {
    			case <-parent.Done():
    				child.cancel(false, parent.Err())
    			case <-child.Done():
    			}
    		}()
    	}
    }
    
    // parentCancelCtx follows a chain of parent references until it finds a
    // *cancelCtx. This function understands how each of the concrete types in this
    // package represents its parent.
    func parentCancelCtx(parent Context) (*cancelCtx, bool) {
    	for {
    		switch c := parent.(type) {
    		case *cancelCtx:
    			return c, true
    		case *timerCtx:
    			return &c.cancelCtx, true
    		case *valueCtx:
    			parent = c.Context
    		default:
    			return nil, false
    		}
    	}
    }
    
    • func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)

      // 对应timerCtx
      // WithDeadline可以设置具体的deadline时间,当到达deadline的时候,可以让后代的goroutine退出,关闭对应的c.done
      func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
      	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) }
      }
      
    • func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

      // 对应timeCtx
      // 可以设置多少时间后就关闭对应的c.done,实现的方式就是计算对应的WithDeadline
      func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
      	return WithDeadline(parent, time.Now().Add(timeout))
      }
      
    • func WithValue(parent Context, key, val interface{}) Context

      // 对应valueCtx
      // 可以在context设置一个map,拿到这个context及后代可以拿到map里的值,也是协程安全的
      func WithValue(parent Context, key, val interface{}) Context {
      	if key == nil {
      		panic("nil key")
      	}
      	if !reflectlite.TypeOf(key).Comparable() {
      		panic("key is not comparable")
      	}
        // 不是在原结构体上直接添加,重新创建一个新的valueCtx子节点,找的时候是由尾部上前查找的
      	return &valueCtx{parent, key, val}
      }
      
  3. context的方法主要有四个

    • Deadline() (deadline time.Time, ok bool)
      // 返回超时时间,可以对一些操作(io等)设置超时时间
      
    • Done() <-chan struct{}
      // 返回一个channel,当context 被取消了,这个channel会被关闭,对应的routine也应该结束返回
      
    • Err() error
      // 如果Done未关闭返回nil,如果已关闭则返回非nil错误解释原因,对Err连续调用将返回相同的错误
      
    • Value(key interface{}) interface{}
      // 可以获取context传递的key对应的一些数据,也是协程安全的
      

context的用法

  1. 使用规则:

    • 不要将 Context放入结构体,Context应该作为第一个参数传入,命名为ctx。
    • 即使函数允许,也不要传入nil的 Context。如果不知道用哪种 Context,可以使用context.TODO()
    • 使用context的Value相关方法,只应该用于在程序和接口中传递和请求相关数据,不能用它来传递一些可选的参数
    • context是协程安全的,可以传递不同的goroutine
  2. 现在重新实现上文简单的控制

    package main
    
    import (
    	"context"
    	"fmt"
    	"time"
    )
    
    func work(ctx context.Context, msg string) {
    	for {
    		select {
    		case <-ctx.Done():
    			println(msg, "goroutinue is finish......")
    			return
    		default:
    			println("goroutinue is running", time.Now().String())
    			time.Sleep(time.Second)
    		}
    	}
    
    }
    
    func main() {
    	ctx, cancel := context.WithCancel(context.Background())
    	go work(ctx, "withCancel")
    	time.Sleep(time.Second * 3)
    	println("cancel......")
    	cancel()
    	time.Sleep(time.Second * 3)
    	println("finish")
    }
    
    
  3. 更多运用

深入context

  1. cancelCtx

    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 (c *cancelCtx) Done() <-chan struct{} {
    	c.mu.Lock()
      // 如果未初始化则初始化lazyload
    	if c.done == nil {
    		c.done = make(chan struct{})
    	}
    	d := c.done
    	c.mu.Unlock()
    	return d
    }
    
    // cancel closes c.done, cancels each of c's children, and, if
    // removeFromParent is true, removes c from its parent's children.
    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)
    	}
      
      // 将所有派生的子节点context依次取消 
    	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)
    	}
    }
    
  2. valueCtx

    type valueCtx struct {
    	Context
    	key, val interface{}
    }
    
    // stringify tries a bit to stringify v, without using fmt, since we don't
    // want context depending on the unicode tables. This is only used by
    // *valueCtx.String().
    func stringify(v interface{}) string {
    	switch s := v.(type) {
    	case stringer:
    		return s.String()
    	case string:
    		return s
    	}
    	return "<not Stringer>"
    }
    
    func (c *valueCtx) String() string {
    	return contextName(c.Context) + ".WithValue(type " +
    		reflectlite.TypeOf(c.key).String() +
    		", val " + stringify(c.val) + ")"
    }
    
    // 沿着context向上寻找key对应的值 =》 对应WithValue
    func (c *valueCtx) Value(key interface{}) interface{} {
    	if c.key == key {
    		return c.val
    	}
    	return c.Context.Value(key)
    }
    
  3. timeCtx

    // 就是在cancelCtx的基础上新增timer属性,使用定时器和deadline去实现定期取消
    type timerCtx struct {
    	cancelCtx
    	timer *time.Timer // Under cancelCtx.mu.
    
    	deadline time.Time
    }
    
    func (c *timerCtx) Deadline() (deadline time.Time, ok bool) {
    	return c.deadline, true
    }
    
    func (c *timerCtx) String() string {
    	return contextName(c.cancelCtx.Context) + ".WithDeadline(" +
    		c.deadline.String() + " [" +
    		time.Until(c.deadline).String() + "])"
    }
    
    func (c *timerCtx) cancel(removeFromParent bool, err error) {
      // 取消内部的cancelCtx
    	c.cancelCtx.cancel(false, err)
    	if removeFromParent {
    		// Remove this timerCtx from its parent cancelCtx's children.
        // 与祖先结点关系取消
    		removeChild(c.cancelCtx.Context, c)
    	}
    	c.mu.Lock()
    	if c.timer != nil {
        // 取消了定时器
    		c.timer.Stop()
    		c.timer = nil
    	}
    	c.mu.Unlock()
    }
    // 如果父节点由过期时间,子节点context可以不用设置过期时间
    
  4. structure图
    context Structure

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章