GO context之WithTimeout的使用


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)
		}
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM