go context of learning

learning context

  • struct context of design
type Context interface {
    Deadline() (deadline time.Time, ok bool)

    Done() <-chan struct{}

    Err() error

    Value(key interface{}) interface{}
}
  • struct fields in the analysis
    • Deadline () returns the setting of the deadline and whether the set deadline
    • Done () returns a read-only chan, used to inform whether or not to release resources
    • Err () returns the reason for the cancellation
    • Value (key interface {}) Get value binding in the context of a key-value pair. This value is thread-safe. (In the case of concurrent, able to correctly handle the shared variable)
  • Examples of common methods of context
    • Reference Code
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"))
}
  • Use packet context

    • Relationship building context tree, realized under control layer Goruntine layer Goruntine. For control of the next layer Goruntine context passed by way of the object variable. Notification control signal Done context object ().
    • Reference example

Guess you like

Origin www.cnblogs.com/MyUniverse/p/11600981.html