WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
c := newCancelCtx(parent)
propagateCancel(parent, &c)
return &c, func() { c.cancel(true, Canceled) }
} // 包了一层,把 parent 赋值给子 context
func newCancelCtx(parent Context) cancelCtx {
return cancelCtx{Context: parent}
} type cancelCtx struct {
Context mu sync.Mutex // protects following fields
done chan struct{} // created lazily, closed by first cancel call
children map[canceler]struct{} // set to nil by the first cancel call
err error // set to non-nil by the first cancel call
}
func propagateCancel(parent Context, child canceler) {
if parent.Done() == nil {
return // parent is never canceled
}
// 判断 parent 是否为 cancelCtx,timerCtx 也属于 cancelCtx,cancelCtx 有 child
if p, ok := parentCancelCtx(parent); ok {
p.mu.Lock()
if p.err != nil {
// cancelCtx 被 cancel() 的时候,会给err属性赋值
// parent has already been canceled
child.cancel(false, p.err)
} else { // parent 没有被 cancel()
if p.children == nil {
p.children = make(map[canceler]struct{})
}
p.children[child] = struct{}{} // 将 child 添加到 parent 中
}
p.mu.Unlock()
} else { // parent 的状态未确定
go func() {
select {
case <-parent.Done(): // 如果可以从 parent 中获取到值,说明 parent 被 cancel 了
child.cancel(false, parent.Err())
case <-child.Done():
}
}()
}
} // 类型判断
func parentCancelCtx(parent Context) (*cancelCtx, bool) {
for {
switch c := parent.(type) {
case *cancelCtx:
return c, true
case *timerCtx:
return &c.cancelCtx, true
case *valueCtx:
parent = c.Context
default:
return nil, false
}
}
}

分析下 WithCancel 返回的函数

func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
c := newCancelCtx(parent)
propagateCancel(parent, &c)
return &c, func() { c.cancel(true, Canceled) }
} func (c *cancelCtx) cancel(removeFromParent bool, err error) {
// 被 cancel 的 cancelCtx 的 err 属性,必须被赋值
if err == nil {
panic("context: internal error: missing cancel error")
}
c.mu.Lock()
if c.err != nil {
c.mu.Unlock()
return // 已经被 cancel
}
c.err = err
if c.done == nil {
c.done = closedchan // 注意此处!!!
} else {
close(c.done) // close 后,select 可以不断获取到默认值
}
// close 掉所有 child
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)
}
} func removeChild(parent Context, child canceler) {
// 只有 cancelCtx 类型的 context,才有 child
p, ok := parentCancelCtx(parent)
if !ok {
return
}
p.mu.Lock()
if p.children != nil {
delete(p.children, child)
}
p.mu.Unlock()
} // closedchan is a reusable closed channel.
// closedchan init() 的时候就被 close 了,所以是可以通过 select 不断获取值的
var closedchan = make(chan struct{})
func init() {
close(closedchan)
}

go context 源码分析的更多相关文章

  1. Context源码分析

    我们做安卓开发,时时都在和Context打交道,那么Context到底是什么?有什么作用?如何与Application,Activity,Service等实例发生联系的?等等 Context是什么? ...

  2. Android源码分析-全面理解Context

    前言 Context在android中的作用不言而喻,当我们访问当前应用的资源,启动一个新的activity的时候都需要提供Context,而这个Context到底是什么呢,这个问题好像很好回答又好像 ...

  3. requirejs源码分析: requirejs 方法–2. context.require(deps, callback, errback);

    上一篇 requirejs源码分析: requirejs 方法–1. 主入口  中的return context.require(deps, callback, errback);  调用的是make ...

  4. ABP源码分析二十四:Notification

    NotificationDefinition: 用于封装Notification Definnition 的信息.注意和Notification 的区别,如果把Notification看成是具体的消息 ...

  5. asp.net mvc 之旅 —— 第六站 ActionFilter的应用及源码分析

    这篇文章我们开始看一下ActionFilter,从名字上其实就大概知道ActionFilter就是Action上的Filter,对吧,那么Action上的Filter大概有几个呢??? 这个问题其实还 ...

  6. 深入理解 spring 容器,源码分析加载过程

    Spring框架提供了构建Web应用程序的全功能MVC模块,叫Spring MVC,通过Spring Core+Spring MVC即可搭建一套稳定的Java Web项目.本文通过Spring MVC ...

  7. jQuery 2.0.3 源码分析 Deferred(最细的实现剖析,带图)

    Deferred的概念请看第一篇 http://www.cnblogs.com/aaronjs/p/3348569.html ******************构建Deferred对象时候的流程图* ...

  8. jQuery 2.0.3 源码分析 Deferred概念

    JavaScript编程几乎总是伴随着异步操作,传统的异步操作会在操作完成之后,使用回调函数传回结果,而回调函数中则包含了后续的工作.这也是造成异步编程困难的主要原因:我们一直习惯于“线性”地编写代码 ...

  9. jQuery-1.9.1源码分析系列(一)整体架构续

    这一节主要是jQuery中最基础的几个东东 2.    jQuery的几个基础属性和函数 a. jQuery.noConflict函数详解 在jQuery初始化的时候保存了外部的$和jQuery _j ...

随机推荐

  1. vue+elementui搭建后台管理界面(4使用font-awesome)

    使用font-awesome npm install --save font-awesome 修改 src/main.js 增加 import 'font-awesome/scss/font-awes ...

  2. Tomcat学习四步走:内核、集群、参数及性能

    主题简介: 内核实现原理 分布式集群 生产部署关键参数 性能监控和分析 一.内核实现原理 HTTP Web服务器与浏览器之间以HTTP协议通信,浏览器要访问服务器即向服务器发送HTTP请求报文. 如图 ...

  3. CEF3设置cookie

    #include "CEF3Helper.h" #include "../include/cef_app.h" #include "../includ ...

  4. 远程桌面工具mRemoteNG与Tsmmc

    一.Tsmmc.msc远程管理工具.1.下载链接:https://pan.baidu.com/s/1tV_xP-ITWyKKzAxLSlGxlw 密码:0jrt 将目录下的mstsmhst.dll.m ...

  5. pt-table-checksum校验与pt-table-sync修复数据【转】

    1:下载工具包 登录网站下载相应的工具包 https://www.percona.com/downloads/percona-toolkit/LATEST/ 2:安装 (1)yum安装: sudo y ...

  6. Mysql中如何查看慢查询以及查看线程

    一.MySQL数据库有几个配置选项可以帮助我们及时捕获低效SQL语句 1,slow_query_log这个参数设置为ON,可以捕获执行时间超过一定数值的SQL语句. 2,long_query_time ...

  7. linux 中 scp 命令

    scp命令用于Linux 之间复制文件和目录.如果想在windows 环境中使用需要安装 linux 命令环境,比如 cmder scp是 secure copy的缩写, scp是linux系统下基于 ...

  8. numpy linspace

    https://www.cnblogs.com/antflow/p/7220798.html numpy.linspace(start, stop, num=50, endpoint=True, re ...

  9. Chrome V75V76新版无法存为mhtml格式解决办法

    升级到75.76版本后谷歌浏览器Chrome V75.0.3770.142 V76.0.3809.87新版,发现无法另存为/保存网页为MHTML了.原来chrome搞了个"Chrome Fl ...

  10. spring 配置事务管理器

    在Spring中数据库事务是通过PlatformTransactionManager进行管理的,jdbcTemplate是不能支持事务的,而能够支持事务的是org.springframework.tr ...