Go之路(三十):context上下文管理
context上下文管理
简单的学习一下,后面会继续深入。
介绍四个方法
1.WithTimeout
2.WithValue
3.WithCancle
4.WithDeadline
类似于一个定时器
package main import( "fmt" "context" "time" ) func main() { ctx,cancle := context.WithTimeout(context.Background(), 2*time.Second) defer cancle() test_chan := make(chan string ,2) go func()(result string){ time.Sleep(1*time.Second) result = "done" test_chan <- result return }() select{ case res :=<- test_chan: fmt.Println("this one",res) case <-ctx.Done(): fmt.Println("other one") } }
这是定时器的用法,第一次创建的ctx可以继承
例如:
package main import( "fmt" "context" ) func run(ctx context.Context){ res,ok := ctx.Value("session").(string) if !ok { res = "???" } fmt.Println(res) id ,_ := ctx.Value("userid").(int) fmt.Println(id) } func main(){ ctx := context.WithValue(context.Background(), "session", "fdhsajk") ctx = context.WithValue(ctx, "userid", 12312321) run(ctx) }