学習の文脈を行きます

学習状況

  • 設計の構造体のコンテキスト
type Context interface {
    Deadline() (deadline time.Time, ok bool)

    Done() <-chan struct{}

    Err() error

    Value(key interface{}) interface{}
}
  • 分析で構造体フィールド
    • 期限()期限の設定を戻し、設定された期限か
    • ()完了を返す読み取り専用のリソースを解放するかどうかを通知するために使用ちゃん、
    • errが()キャンセルの理由を返します。
    • 値(キーインターフェイス{})キーと値のペアの文脈で結合値を取得します。この値は、スレッドセーフです。(正確に共有変数を扱うことができる同時の場合には)
  • コンテキストの一般的な方法の例
    • 参照コード
package main

import(
    "fmt"
    "time"
    "golang.org/x/net/context"
)

type faveContextKey string   //定义别名

func main(){
    fmt.Println("context包学习")
    UseContext()
    UseContextWithDeadline()
    UseContextWithTimeout()
    UseContextWithValue()
}


func UseContext(){
    // 使用withCancel生成上下文
    gen := func (ctx context.Context)<- chan int{
        dst := make(chan int)  //无缓冲,无长度
        n := 1
        fmt.Println("这个函数被调用多少次:",n)  //被调用一次
        go func (){
            for{
                select{
                // 多个case同时满足,就会随机执行case
                case <- ctx.Done():
                    // 关闭上下文
                    fmt.Println("ctx.Done",ctx.Err(),n)
                    return
                case dst <- n:   //要么运行完这个作用域,要么就不用运行
                    n++
                    fmt.Printf("n = %v \n",n)
                }
            }
        }()
        //发送器
        return dst
    }
    ctx,cancel := context.WithCancel(context.Background())
    defer cancel()
    data := gen(ctx)
    for n:= range data{  //接收
        fmt.Println(n)
        if n== 16{
            break
        }
    }
}


func UseContextWithDeadline(){
    // withDeadline作用:设置context的存活期
    d := time.Now().Add(50 * time.Millisecond)
    ctx,cancel := context.WithDeadline(context.Background(),d)
    if ctx == nil{
        fmt.Println("ctx is nil")
        return
    }
    defer cancel()
    select{
    case <-time.After(time.Second*1):
        fmt.Println("overslept")
    case <- ctx.Done():
        fmt.Println(ctx.Err())
    }
}


func UseContextWithTimeout(){
    // withTimeout作用:设置context的存活期
    ctx,cancel := context.WithTimeout(context.Background(),50*time.Millisecond)
    if ctx == nil{
        fmt.Println("ctx is nil")
        return
    }
    defer cancel()
    select{
    case <-time.After(time.Second*1):
        fmt.Println("overslept")
    case <- ctx.Done():
        fmt.Println(ctx.Err())
    }
}

func UseContextWithValue(){
    // withValue作用:带值
    f := func(ctx context.Context,k faveContextKey){
        if v := ctx.Value(k);v!=nil{
            fmt.Printf("key:%v,value:%v \n",k,v)
        }else{
            fmt.Println("key not found!",k)
        }
    }
    k := faveContextKey("language")
    ctx:= context.WithValue(context.Background(),k,"go")
    if ctx==nil{
        fmt.Println("ctx is nil")
    }
    f(ctx,k)
    f(ctx,faveContextKey("color"))
}
  • パケットコンテキストを使用します

    • 制御層Goruntine層Goruntineの下に実現関係の建物のコンテキストツリー、。次の層の制御のためGoruntineコンテキストは、オブジェクト変数を介して渡されます。通知制御信号完了コンテキストオブジェクト()。
    • 参考用例

おすすめ

転載: www.cnblogs.com/MyUniverse/p/11600981.html