赞
踩
context包的context的接口,主要是控制协程执行上下文的时间,以及取消程序的执行,以及上下文中传递数据等作用,golang中耗时或者需要协同的操作都会见到context的身影。
context有几个常用的方法
创建一个空白的,顶级的,不会被取消的上下文。
创建一个有执行时间限制的上下文
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
return WithDeadline(parent, time.Now().Add(timeout))
}
可以通过ctx.Done()方法获取上下超时的通知。
package main import ( "context" "fmt" "time" ) func main() { parentCxt := context.Background() ctx, cancel := context.WithTimeout(parentCxt, time.Second*5) go longTimeTask(ctx) time.Sleep(time.Second * 10) cancel() fmt.Println("task cancel success") } func longTimeTask(ctx context.Context) { for { //fmt.Println("ok") select { case <-time.After(time.Second * 1): fmt.Println("task compete") case <-ctx.Done(): fmt.Println("time out") return } } }
获取一个可以中止的上下文,该方法会返回一个新的context,和cancel函数,调用cancel函数后,通过ctx.Done()方法可以获取到上下文取消的通知
package main import ( "context" "fmt" "time" ) func main() { parentCxt := context.Background() ctx, cancel := context.WithCancel(parentCxt) go longTimeTask(ctx) time.Sleep(time.Second * 10) cancel() fmt.Println("task cancel success") } func longTimeTask(ctx context.Context) { for { //fmt.Println("ok") select { case <-time.After(time.Second * 1): fmt.Println("task compete") case <-ctx.Done(): fmt.Println("time out") return } } }
func WithValue(parent Context, key, val any) Context {
if parent == nil {
panic(“cannot create context from nil parent”)
}
if key == nil {
panic(“nil key”)
}
if !reflectlite.TypeOf(key).Comparable() {
panic(“key is not comparable”)
}
return &valueCtx{parent, key, val}
}
可以在上下文中存贮一些参数,通过上下文随时获取。
golang的chan和map,切片,接口,函数一样是引用类型。
golang更加推荐使用chan去解决并发的协作的问题,对chan的读写是并发安全的,当然你也可也以使用sync.Mutex等包来控制并发。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。