Golang context是什么,能做什么
Go 语言在1.7版本的标准库引入了“context”,这个库几乎成为了并发控制和超时控制的标准做法。
比如一个网络请求Request,每个Request都需要开启一个goroutine做一些事情,这些goroutine又可能会开启其他的goroutine。所以我们需要一种可以跟踪goroutine的方案,才可以达到控制他们的目的。
使用方法
第一步:使用 context.Background() 函数创建一个Context树的根节点。
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
第二步: 使用With系列函数创建Context父节点。有四种函数,分别如下
ctx, cancel := context.WithCancel(context.Background())
ctx1,cancel1 := context.WithTimeout(context.Background(),1*time.Second)
ctx2,cancel2 := context.WithDeadline(context.Background(), time.Now().Add(time.Second*3))
ctx3 := context.WithValue(context.Background(),"ch","value")
第三步:使用cancel()函数通知子Context的Done通道发送消息
第四步:在goroutine中使用ctx.Done()监听退出通道数据