码农后生

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

GO context之WithTimeout的使用

  • 转载 https://blog.csdn.net/yzf279533105/article/details/107292247
  • 它主要的用处如果用一句话来说,是在于控制goroutine的生命周期。当一个计算任务被goroutine承接了之后,由于某种原因(超时,或者强制退出)我们希望中止这个goroutine的计算任务,那么就用得到这个Context了。

使用方法

      func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
      //
      
      func Background() Context
      //Background返回一个非空的Context。 它永远不会被取消,没有价值,也没有期限。 它通常由主要功能,初始化和测试使用,并用作传入请求的顶级上下文。

      type Context interface {
          // Deadline returns the time when work done on behalf of this context
          // should be canceled. Deadline returns ok==false when no deadline is
          // set. Successive calls to Deadline return the same results.
          Deadline() (deadline time.Time, ok bool)

          // Done returns a channel that's closed when work done on behalf of this
          // context should be canceled. Done may return nil if this context can
          // never be canceled. Successive calls to Done return the same value.
          //
          // WithCancel arranges for Done to be closed when cancel is called;
          // WithDeadline arranges for Done to be closed when the deadline
          // expires; WithTimeout arranges for Done to be closed when the timeout
          // elapses.
          //
          // Done is provided for use in select statements:
          //
          //  // Stream generates values with DoSomething and sends them to out
          //  // until DoSomething returns an error or ctx.Done is closed.
          //  func Stream(ctx context.Context, out chan<- Value) error {
          //  	for {
          //  		v, err := DoSomething(ctx)
          //  		if err != nil {
          //  			return err
          //  		}
          //  		select {
          //  		case <-ctx.Done():
          //  			return ctx.Err()
          //  		case out <- v:
          //  		}
          //  	}
          //  }
          //
          // See https://blog.golang.org/pipelines for more examples of how to use
          // a Done channel for cancelation.
          Done() <-chan struct{}

          // Err returns a non-nil error value after Done is closed. Err returns
          // Canceled if the context was canceled or DeadlineExceeded if the
          // context's deadline passed. No other values for Err are defined.
          // After Done is closed, successive calls to Err return the same value.
          Err() error

         // Value returns the value associated with this context for key, or nil
          // if no value is associated with key. Successive calls to Value with
          // the same key returns the same result.
          //
          // Use context values only for request-scoped data that transits
          // processes and API boundaries, not for passing optional parameters to
          // functions.
          //
          // A key identifies a specific value in a Context. Functions that wish
          // to store values in Context typically allocate a key in a global
          // variable then use that key as the argument to context.WithValue and
          // Context.Value. A key can be any type that supports equality;
          // packages should define keys as an unexported type to avoid
          // collisions.
          //
          // Packages that define a Context key should provide type-safe accessors
          // for the values stored using that key:
          //
          // 	// Package user defines a User type that's stored in Contexts.
          // 	package user
          //
          // 	import "context"
          //
          // 	// User is the type of value stored in the Contexts.
          // 	type User struct {...}
          //
          // 	// key is an unexported type for keys defined in this package.
          // 	// This prevents collisions with keys defined in other packages.
          // 	type key int
          //
          // 	// userKey is the key for user.User values in Contexts. It is
          // 	// unexported; clients use user.NewContext and user.FromContext
          // 	// instead of using this key directly.
          // 	var userKey key = 0
          //
          // 	// NewContext returns a new Context that carries value u.
          // 	func NewContext(ctx context.Context, u *User) context.Context {
          // 		return context.WithValue(ctx, userKey, u)
          // 	}
          //
          // 	// FromContext returns the User value stored in ctx, if any.
          // 	func FromContext(ctx context.Context) (*User, bool) {
          // 		u, ok := ctx.Value(userKey).(*User)
          // 		return u, ok
          // 	}
          Value(key interface{}) interface{}
         }
      1. context包的WithTimeout()函数接受一个 Context 和超时时间作为参数,返回其子Context和取消函数cancel

      2. 新创建协程中传入子Context做参数,且需监控子Context的Done通道,若收到消息,则退出

      3. 需要新协程结束时,在外面调用 cancel 函数,即会往子Context的Done通道发送消息

      4. 若不调用cancel函数,到了原先创建Contetx时的超时时间,它也会自动调用cancel()函数,即会往子Context的Done通道发送消息
package main
 
import (
	"context"
	"fmt"
	"time"
)
 
func main() {
	// 创建一个子节点的context,3秒后自动超时
        // 利用根Context创建一个父Context,使用父Context创建2个协程,超时时间设为3秒
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
 
	go watch(ctx, "监控1")
	go watch(ctx, "监控2")
 
	fmt.Println("现在开始等待8秒,time=", time.Now().Unix())
	time.Sleep(8 * time.Second)
       
        //等待8秒钟,再调用cancel函数,其实这个时候会发现在3秒钟的时候两个协程已经收到退出信号了
	fmt.Println("等待8秒结束,准备调用cancel()函数,发现两个子协程已经结束了,time=", time.Now().Unix())
	cancel()
}
 
// 单独的监控协程
func watch(ctx context.Context, name string) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println(name, "收到信号,监控退出,time=", time.Now().Unix())
			return
		default:
			fmt.Println(name, "goroutine监控中,time=", time.Now().Unix())
			time.Sleep(1 * time.Second)
		}
	}
}
posted on 2020-11-16 14:51  码农后生  阅读(2804)  评论(0编辑  收藏  举报