context包主要用来控制goroutings间的并发控制。使用场景包括通知子协程退出这种。

相关接口和示例:

func Background() Context
Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline.
It is typically used by the main function, initialization, and tests, and as the top-level Context for
incoming requests.该函数返回一个空的ctx,该ctx不能被取消,没有值并且没有deadline。通常用于主函数、初始化或者测试中,用作顶层的ctx。func TODO() Context
TODO returns a non-nil, empty Context. Code should use context.TODO when it's unclear which Context to use
or it is not yet available (because the surrounding function has not yet been extended to accept
a Context parameter).TODO方法和Background方法的实现以一样的,区别在于TODO能够被静态分析工具识别。func WithCancel(parent Context) (ctx Context, cancel CancelFunc)WithCancel returns a copy of parent with a new Done channel. The returned context's Done channel is closed
when the returned cancel function is called or when the parent context's Done channel is closed, whichever
happens first.WithCancel 返回父ctx的一份复制和一个新的Done 通道,返回的ctx Done通道只有在cancel方法被调用或者父ctx被取消才返回。

withCancel示例一,调用cancel方法通知子协程取消:

package mainimport ("context""fmt""time"
)func main() {//定义一个空的ctxrootCtx := context.TODO()//从根ctx衍生子ctxctx, cancel := context.WithCancel(rootCtx)go func() {for {select {case <-ctx.Done():fmt.Printf("cancel called, gorouting exit\n")returncase <-time.After(1 * time.Second):fmt.Println("gorouting running...")}}}()fmt.Println("main routing sleep 3s")time.Sleep(time.Second * 3)//调用cancel取消子线程cancel()fmt.Println("main routing call cancel")time.Sleep(1 * time.Second)
}

运行截图:

withCancel示例二,取消父ctx,子协程一并退出:

package mainimport ("context""fmt""time"
)func main() {//建立一个父contextparentCtx, cancel := context.WithCancel(context.Background())go func() {//从父context衍生出子contextchildCtx, _ := context.WithCancel(parentCtx)go func() {//子协程运行for {select {case <-childCtx.Done():fmt.Printf("childCtx Done, Child exit\n")returncase <-time.After(time.Second * 2):fmt.Println("Child is running...")}}}()//父协程运行for {select {case <-parentCtx.Done():fmt.Println("parentCtx Done, Parent exit")returncase <-time.After(time.Second * 6):fmt.Println("parent is running...")}}}()time.Sleep(8 * time.Second)fmt.Printf("Time Up, Close parentCtx\n")//取消父contextcancel()time.Sleep(4 * time.Second)
}

运行截图:

func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)WithDeadline和withCancel类似,只不过增加了一个截止时间,时间到了,该ctx的Done通道会自动关闭。

WithDeadline用例:

package mainimport ("context""fmt""time"
)func main() {//衍生一个3s的ctxctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*3))//好的编码习惯是主动调用cancel,即便ctx自动超时过期。defer cancel()for {select {case <-ctx.Done():fmt.Println("ctx Done")returncase <-time.After(1 * time.Second):fmt.Println("time up...")}}
}

运行截图:

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).这个方法和WithDeadline类似
func WithValue(parent Context, key, val interface{}) ContextWithValue方法可以绑定一个键值对,使得后续衍生出来的ctx都能够获取这个值。WithValue返回父类的副本,其中与键关联的值为val。仅对传输流程和api的请求范围的数据使用上下文值,而不是将可选参数传递给函数。所提供的键必须是可比较的,并且不应该是string类型或任何其他内置类型,以避免使用上下文在包之间发
生冲突。WithValue的用户应该为键定义自己的类型。为了避免在分配给接口{}时进行分配,上下文键通常
具有具体类型struct{}。或者,导出的上下文关键变量的静态类型应该是指针或接口。

WithValue用例:

package mainimport ("context""fmt"
)func main() {type ContextKey stringf := func(ctx context.Context, k ContextKey) {if v := ctx.Value(k); v != nil {fmt.Println("found value:", v)return}fmt.Println("key not found:", k)}//绑定键值对{"language":"Go"}k := ContextKey("language")ctx := context.WithValue(context.Background(), k, "Go")f(ctx, k)f(ctx, ContextKey("color"))}

运行截图:

参考资料:

1.https://golang.org/pkg/context/

2. Go语言实战笔记(二十)| Go Context,https://www.flysnow.org/2017/05/12/go-in-action-go-context.html

Golang Context包的使用相关推荐

  1. golang context包

    一.介绍 go中有Context 包,专门用来简化 对于处理单个请求的多个 goroutine 之间与请求域的数据.取消信号.截止时间等相关操作,这些操作可能涉及多个 API 调用.你可以通过 go ...

  2. golang - context包使用示例 以及 底层实现

    文章目录 1. context 常用方法,以及各种适用于什么场景 1.1 context含有的方法 1.2 方法适用场景和伪代码示例 1.2.1 值传递:比如gin框架中用来传递key,value的值 ...

  3. 深入理解Golang中的Context包

    context.Context是Go语言中独特的设计,在其他编程语言中我们很少见到类似的概念.context.Context深度支持Golang的高并发. 1. Goroutine和Channel 在 ...

  4. golang context 父子任务同步取消信号 协程调度 简介

    目录 前言 为什么需要context context是什么 context的使用 总结 前言 这篇文章将介绍Golang并发编程中常用到一种编程模式:context.本文将从为什么需要context出 ...

  5. 并发安全Context包的使用

    前言–为什么需要Context Golang context是Golang应用开发常用的并发控制技术,它与WaitGroup最大的不同点是context对于派生goroutine有更强的控制力,它可以 ...

  6. Golang Context 详细原理和使用技巧

    文章目录 Golang Context 详细原理和使用技巧 Context 背景 和 适用场景 Context 的背景 Context 的功能和目的 Context 的基本使用 Context 的同步 ...

  7. Golang context.Context

    这里填写标题 1. Golang context.Context 1.1. 内容前导 1.2. 基础知识 1.2.1. Context 接口 1.2.2. 顶层 Context 1.2.3. 子 Co ...

  8. gorrilla Context包深入学习

    导语 做过web开发的同学肯定都知道,我们经常使用 r *http.Request 这个变量来获取我们希望获得的参数,但是我们经常遇到这样一个场景,我们需要为我们的r设置更多的key-value形式的 ...

  9. 一文搞懂Go标准库context包

    "Gopher部落"星球双11现金优惠,点击链接领劵 https://t.zsxq.com/078E1QTjM  立减88元. 自从context包在Go 1.7版本[1]加入Go ...

最新文章

  1. suse11/12关闭防火墙
  2. Python入门第三章--第一节:条件判断语句
  3. jQuery easyUI--accordion折叠面板
  4. robcad和catia是什么关系_proe/CATIA/UG/SolidWorks软件区别与联系
  5. java 轻量数据库_DBTree是一个springboot2 + vue-element-template实现的轻量数据库表结构查看及管理工具...
  6. 单处理器调度算法详解
  7. 让自己强大,必须放下十样东西
  8. c#多通道波形显示_因为每秒要采集50多个波形,需要大量的数据分析和波形分析,有什么好的解决办法吗?...
  9. 北上广深的请注意,阿里聚安全来找你玩啦~
  10. 再接再厉!Alphabet将携手更多汽车厂商测试无人驾驶
  11. 验证码——ImageIO.write的坑
  12. Codeforces #123D: 后缀数组+单调栈
  13. vscode配置及快捷键(未完成待续)
  14. 以太坊平台评估 私有链和联盟链的机会与挑战
  15. UI设计,扁平化还是拟物化?
  16. 就知道你喜欢中文版:Spread .NET 15.2 FOR WPF
  17. SpringCloud Gateway堆外内存溢出排查
  18. 12.4 Borüvka算法
  19. 计算机网络8832,3C8832路由器中DDN中的应用设置
  20. DCMM认证评估机构,你都知道吗?

热门文章

  1. Linux下程序包管理工具RPM
  2. log4j的NDC/MDC区别与应用
  3. NSPredicate的用法
  4. 扫盲行动之九:Vi编辑器的基本使用方法!
  5. 摘自《读者》的哲理短句——赞美篇
  6. ios请求头解决参数中文乱码_解决请求参数的中文乱码问题(get、post)
  7. java ror框架搭建_ROR 环境的 搭建
  8. 5.1 代价函数-机器学习笔记-斯坦福吴恩达教授
  9. stm32 常见错误及原因【持续更新】
  10. Android显示系统之View与SurfaceView更新屏幕的区别