简介

golang 中的创建一个新的 goroutine , 并不会返回像c语言类似的pid,所有我们不能从外部杀死某个goroutine,所有我就得让它自己结束,之前我们用 channel + select 的方式,来解决这个问题,但是有些场景实现起来比较麻烦,例如由一个请求衍生出的各个 goroutine 之间需要满足一定的约束关系,以实现一些诸如有效期,中止routine树,传递请求全局变量之类的功能。于是google 就为我们提供一个解决方案,开源了 context 包。使用 context 实现上下文功能约定需要在你的方法的传入参数的第一个传入一个 context.Context 类型的变量。

源码剖析

context.Context 接口

context 包的核心

//  context 包里的方法是线程安全的,可以被多个 goroutine 使用
type Context interface {
// 当Context 被 canceled 或是 times out 的时候,Done 返回一个被 closed 的channel
Done() <-chan struct{} // 在 Done 的 channel被closed 后, Err 代表被关闭的原因
Err() error // 如果存在,Deadline 返回Context将要关闭的时间
Deadline() (deadline time.Time, ok bool) // 如果存在,Value 返回与 key 相关了的值,不存在返回 nil
Value(key interface{}) interface{}
}

我们不需要手动实现这个接口,context 包已经给我们提供了两个,一个是 Background(),一个是 TODO(),这两个函数都会返回一个 Context 的实例。只是返回的这两个实例都是空 Context。

主要结构

cancelCtx 结构体继承了 Context ,实现了 canceler 方法:

点击查看代码
//*cancelCtx 和 *timerCtx 都实现了canceler接口,实现该接口的类型都可以被直接canceled
type canceler interface {
cancel(removeFromParent bool, err error)
Done() <-chan struct{}
} type cancelCtx struct {
Context
done chan struct{} // closed by the first cancel call.
mu sync.Mutex
children map[canceler]bool // set to nil by the first cancel call
err error // 当其被cancel时将会把err设置为非nil
} func (c *cancelCtx) Done() <-chan struct{} {
return c.done
} func (c *cancelCtx) Err() error {
c.mu.Lock()
defer c.mu.Unlock()
return c.err
} func (c *cancelCtx) String() string {
return fmt.Sprintf("%v.WithCancel", c.Context)
} //核心是关闭c.done
//同时会设置c.err = err, c.children = nil
//依次遍历c.children,每个child分别cancel
//如果设置了removeFromParent,则将c从其parent的children中删除
func (c *cancelCtx) cancel(removeFromParent bool, err error) {
if err == nil {
panic("context: internal error: missing cancel error")
}
c.mu.Lock()
if c.err != nil {
c.mu.Unlock()
return // already canceled
}
c.err = err
close(c.done)
for child := range c.children {
// NOTE: acquiring the child's lock while holding parent's lock.
child.cancel(false, err)
}
c.children = nil
c.mu.Unlock() if removeFromParent {
removeChild(c.Context, c) // 从此处可以看到 cancelCtx的Context项是一个类似于parent的概念
}
}
  • timerCtx 结构继承 cancelCtx
type timerCtx struct {
cancelCtx //此处的封装为了继承来自于cancelCtx的方法,cancelCtx.Context才是父亲节点的指针
timer *time.Timer // Under cancelCtx.mu. 是一个计时器
deadline time.Time
}
  • valueCtx 结构继承 cancelCtx
type valueCtx struct {
Context
key, val interface{}
}

主要方法

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
func WithValue(parent Context, key interface{}, val interface{}) Context

WithCancel 对应的是 cancelCtx ,其中,返回一个 cancelCtx ,同时返回一个 CancelFunc,CancelFunc 是 context 包中定义的一个函数类型:type CancelFunc func()。调用这个 CancelFunc 时,关闭对应的c.done,也就是让他的后代goroutine退出。

WithDeadline 和 WithTimeout 对应的是 timerCtx ,WithDeadline 和 WithTimeout 是相似的,WithDeadline 是设置具体的 deadline 时间,到达 deadline 的时候,后代 goroutine 退出,而 WithTimeout 简单粗暴,直接 return WithDeadline(parent, time.Now().Add(timeout))。

WithValue 对应 valueCtx ,WithValue 是在 Context 中设置一个 map,拿到这个 Context 以及它的后代的 goroutine 都可以拿到 map 里的值。

使用原则

使用 Context 的程序包需要遵循如下的原则来满足接口的一致性以及便于静态分析

不要把 Context 存在一个结构体当中,显式地传入函数。Context 变量需要作为第一个参数使用,一般命名为ctx

即使方法允许,也不要传入一个 nil 的 Context ,如果你不确定你要用什么 Context 的时候传一个 context.TODO

使用 context 的 Value 相关方法只应该用于在程序和接口中传递的和请求相关的元数据,不要用它来传递一些可选的参数

同样的 Context 可以用来传递到不同的 goroutine 中,Context 在多个goroutine 中是安全的

使用示例

  1. 带超时时间的自动取消
点击查看代码
func main() {
var a, b = 1, 2
ctx, cancel := context.WithTimeout(context.Background(), time.Second * 3 + time.Millisecond * 10)
defer cancel()
ret := Add(ctx, a, b)
fmt.Printf("%d + %d = %d", a, b, ret)
} func Add(ctx context.Context, a, b int) int {
var res int
for i := 0; i < a; i++ {
res = Inc(res)
select {
case <-ctx.Done():
return -1
default:
}
}
for i := 0; i < b; i++ {
res = Inc(res)
select {
case <-ctx.Done():
return -1
default:
}
}
return res
}
func Inc(res int) int {
res += 1
time.Sleep(time.Second * 1)
return res
}
  1. 主动取消
点击查看代码
func main() {
var a, b = 1, 2
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(3 * time.Second + 25 * time.Millisecond)
cancel()
}()
ret := Add(ctx, a, b)
fmt.Printf("%d + %d = %d", a, b, ret)
} func Add(ctx context.Context, a, b int) int {
var res int
for i := 0; i < a; i++ {
res = Inc(res)
select {
case <-ctx.Done():
return -1
default:
}
}
for i := 0; i < b; i++ {
res = Inc(res)
select {
case <-ctx.Done():
return -1
default:
}
}
return res
}
func Inc(res int) int {
res += 1
time.Sleep(time.Second * 1)
return res
}

golang中的标准库context解读的更多相关文章

  1. golang中的标准库context

    在 Go http包的Server中,每一个请求在都有一个对应的 goroutine 去处理.请求处理函数通常会启动额外的 goroutine 用来访问后端服务,比如数据库和RPC服务.用来处理一个请 ...

  2. golang中的标准库数据格式

    数据格式介绍 是系统中数据交互不可缺少的内容 这里主要介绍JSON.XML.MSGPack JSON json是完全独立于语言的文本格式,是k-v的形式 name:zs 应用场景:前后端交互,系统间数 ...

  3. golang中的标准库log

    Go语言内置的log包实现了简单的日志服务.本文介绍了标准库log的基本使用. 使用Logger log包定义了Logger类型,该类型提供了一些格式化输出的方法.本包也提供了一个预定义的" ...

  4. golang中的标准库http

    Go语言内置的net/http包十分的优秀,提供了HTTP客户端和服务端的实现. http客户端 基本的HTTP/HTTPS请求 Get.Head.Post和PostForm函数发出HTTP/HTTP ...

  5. golang中的标准库template

    html/template包实现了数据驱动的模板,用于生成可对抗代码注入的安全HTML输出.它提供了和text/template包相同的接口,Go语言中输出HTML的场景都应使用text/templa ...

  6. golang中的标准库IO操作

    参考链接 输入输出的底层原理 终端其实是一个文件,相关实例如下: os.Stdin:标准输入的文件实例,类型为*File os.Stdout:标准输出的文件实例,类型为*File os.Stderr: ...

  7. golang中的标准库time

    时间类型 time.Time类型表示时间.我们可以通过time.Now()函数获取当前的时间对象,然后获取时间对象的年月日时分秒等信息.示例代码如下: func main() { current := ...

  8. golang中的标准库反射

    反射 反射是指程序在运行期对程序本身访问和修改的能力 变量的内在机制 变量包含类型信息和值信息 var arr [10]int arr[0] = 10 类型信息:是静态的元信息,是预先定义好的 值信息 ...

  9. golang中的标准库strconv

    strconv 包 strconv包实现了基本数据类型与其字符串表示的转换,主要有以下常用函数: Atoi().Itia().parse系列.format系列.append系列. string与int ...

随机推荐

  1. windows下php安装redis扩展

    查看当前PHP版本 代码中添加 phpinfo(); 下载对应的redis扩展 下载链接:https://pecl.php.net/package/redis 因为我的PHP版本是5.6的,所以red ...

  2. 【LeetCode】280. Wiggle Sort 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 排序后交换相邻元素 日期 题目地址:https://l ...

  3. 【剑指Offer】09. 用两个栈实现队列 解题报告(python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人微信公众号:负雪明烛 目录 题目描述 解题方法 一个栈用来保存输入,一个栈用来输出 日 ...

  4. 另一个角度看元宇宙与RPA:人工世界、平行员工与RPA

    另一个角度看元宇宙与RPA:人工世界.平行员工与RPA 从元宇宙到平行员工,人工世界推动的虚实分工利好RPA 机器人是铁打营盘人类是流水兵,未来元宇宙的虚实分工RPA机会巨大 文/王吉伟 元宇宙是平行 ...

  5. HPU积分赛 2019.8.18

    A题 给出n个数,问这n个数能不能分成奇数个连续的长度为奇数并且首尾均为奇数的序列 Codeforces849A 题解传送门 代码 1 #include <bits/stdc++.h> 2 ...

  6. Cython编译动态库、引用C/C++文件

    将某些.py 编译成动态库 设置好要编译的module们: compile_to_c_modules = [ 'package.module' ] 将它们转换成cythonize可识别的参数: def ...

  7. 使用 JavaScript 中的 document 对象的属性,根据下拉框中选择的属性,更改页面中的字体颜色和背景颜色

    查看本章节 查看作业目录 需求说明: 使用 JavaScript 中的 document 对象的属性,根据下拉框中选择的属性,更改页面中的字体颜色和背景颜色 实现思路: 在页面的 <body&g ...

  8. PHP 的扩展类型及安装方式

    扩展类型 底层扩展(基于C语言): PECL 上层扩展(基于PHP 语言): PEAR Composer PECL # 查找扩展 $ pecl search extname # 安装扩展 $ pecl ...

  9. Python_关于python2的encode(编码)和decode(解码)的使用

    在使用Python2时,我们习惯于在文件开头声明编码 # coding: utf-8 不然在文件中出现中文,运行时就会报错 SyntaxError: Non-ASCII character... 之类 ...

  10. Python_闭包

    闭包并不只是一个python中的概念,在函数式编程语言中应用较为广泛.理解python中的闭包一方面是能够正确的使用闭包,另一方面可以好好体会和思考闭包的设计思想. 1.概念介绍 首先看一下维基上对闭 ...