golang context

作用:用于在go协程中 传递上下文、超时、取消、传值

底层实现:是由互斥锁、channel、map来实现的
互斥锁:保护临界资源
channel: 用于信号通知,比如ctx.Done()
map: 保存父ctx下派生的所有子ctx, 父ctx关闭,子ctx都关闭

实现的接口

type Context interface {Deadline() (deadline time.Time, ok bool)Done() <-chan struct{}Err() errorValue(key interface{}) interface{}
}

空ctx

type emptyCtx intfunc (*emptyCtx) Deadline() (deadline time.Time, ok bool) {return
}func (*emptyCtx) Done() <-chan struct{} {return nil
}func (*emptyCtx) Err() error {return nil
}func (*emptyCtx) Value(key interface{}) interface{} {return nil
}

cancel ctx

使用map保存所有子ctx,确保父ctx cancel后,子ctx也cancel

type cancelCtx struct {Contextmu       sync.Mutex            // protects following fieldsdone     chan struct{}         // created lazily, closed by first cancel callchildren map[canceler]struct{} // set to nil by the first cancel callerr      error                 // set to non-nil by the first cancel call
}func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {if parent == nil {panic("cannot create context from nil parent")}c := newCancelCtx(parent)propagateCancel(parent, &c)return &c, func() { c.cancel(true, Canceled) }
}// newCancelCtx returns an initialized cancelCtx.
func newCancelCtx(parent Context) cancelCtx {return cancelCtx{Context: parent}
}func propagateCancel(parent Context, child canceler) {fmt.Println("propagateCancel")done := parent.Done()if done == nil {return // parent is never canceled}select {case <-done:// parent is already canceledchild.cancel(false, parent.Err())returndefault:}if p, ok := parentCancelCtx(parent); ok {p.mu.Lock()if p.err != nil {// parent has already been canceledchild.cancel(false, p.err)} else {if p.children == nil {p.children = make(map[canceler]struct{})}// 保存子ctxp.children[child] = struct{}{}}p.mu.Unlock()} else {atomic.AddInt32(&goroutines, +1)go func() {select {case <-parent.Done():child.cancel(false, parent.Err())case <-child.Done():}}()}
}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 = errif c.done == nil {c.done = closedchan} else {close(c.done) // 关闭channel, 用于通知ctx.Done()}// 关闭所有子ctxfor child := range c.children {// NOTE: acquiring the child's lock while holding parent's lock.child.cancel(false, err)}c.children = nilc.mu.Unlock()if removeFromParent {removeChild(c.Context, c)}
}

timeout ctx

在cancelctx的基础上实现,只是多了个定时器自动调用cancel

type timerCtx struct {cancelCtxtimer *time.Timer // Under cancelCtx.mu.deadline time.Time
}func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {if parent == nil {panic("cannot create context from nil parent")}if cur, ok := parent.Deadline(); ok && cur.Before(d) {// The current deadline is already sooner than the new one.return WithCancel(parent)}c := &timerCtx{cancelCtx: newCancelCtx(parent),deadline:  d,}propagateCancel(parent, c)dur := time.Until(d)if dur <= 0 {c.cancel(true, DeadlineExceeded) // deadline has already passedreturn c, func() { c.cancel(false, Canceled) }}c.mu.Lock()defer c.mu.Unlock()if c.err == nil {c.timer = time.AfterFunc(dur, func() {c.cancel(true, DeadlineExceeded)})}return c, func() { c.cancel(true, Canceled) }
}

value ctx

type valueCtx struct {Contextkey, val interface{}
}
func WithValue(parent Context, key, val interface{}) 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}
}
func (c *valueCtx) Value(key interface{}) interface{} {if c.key == key {return c.val}return c.Context.Value(key)
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/809235.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Redis Pipelining 底层原理分析及实践

作者&#xff1a;vivo 互联网服务器团队-Wang Fei Redis是一种基于客户端-服务端模型以及请求/响应的TCP服务。在遇到批处理命令执行时&#xff0c;Redis提供了Pipelining(管道)来提升批处理性能。本文结合实践分析了Spring Boot框架下Redis的Lettuce客户端和Redisson客户端对…

linux c多线程简单队列实现

编译环境&#xff1a;Ubuntu16.04 64位 交叉编译工具&#xff1a;arm-hisiv500-linux-gcc 文章目录 1. 背景2. 涉及的函数3. 头文件JList.h4. 类的实现 1. 背景 最近项目中需要用到多线程通信&#xff0c;自己造个轮子吧&#xff0c;对照上一篇linux c共享内存和信号量。 2. …

python如何学习数据分析

学习使用 Python 进行数据分析是一个循序渐进的过程&#xff0c;需要掌握基本的 Python 编程技能&#xff0c;并了解数据处理、数据可视化和常用的数据分析工具和库。以下是学习 Python 数据分析的步骤和建议&#xff1a; 1. 掌握 Python 编程基础 在开始学习数据分析之前&am…

Unity构建详解(7)——AssetBundle格式解析

【文件格式】 文件可以分为文本文件、图片文件、音频文件、视频文件等等&#xff0c;我们常见的这些文件都有行业内的标准格式&#xff0c;其意味着按照一定的规则和规范去保存读取文件&#xff0c;可以获取我们想要的数据。 有些软件会有自己的文件格式&#xff0c;会按照其…

神经网络和反向传播算法

1. 理解神经网络的基础 开始于感知器&#xff1a;首先理解感知器&#xff08;Perceptron&#xff09;模型&#xff0c;这是最简单的神经网络形式。感知器接收多个输入&#xff0c;通过加权和并应用激活函数来产生输出。这为理解更复杂的神经网络奠定了基础。多层网络&#xff…

风储微网虚拟惯性控制系统simulink建模与仿真

目录 1.课题概述 2.系统仿真结果 3.核心程序与模型 4.系统原理简介 5.完整工程文件 1.课题概述 风储微网虚拟惯性控制系统simulink建模与仿真。风储微网虚拟惯性控制系统是一种模仿传统同步发电机惯性特性的控制策略&#xff0c;它通过集成风力发电系统、储能系统和其他分…

rk3588 安卓13 应用安装白名单的接口

文章目录 概述一、app应用安装白名单核心代码二、app应用安装白名单核心功能分析三、代码实战1.先导入所需要的包2.添加获取白名单方法3.添加限制白名单方法4.上层使用PS:查看当前白名单 总结 概述 在13.0系统rom定制化开发中&#xff0c;客户需求要实现应用安装白名单功能&am…

如何动态渲染HTML内容?用v-html!

&#x1f90d; 前端开发工程师、技术日更博主、已过CET6 &#x1f368; 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1 &#x1f560; 牛客高级专题作者、打造专栏《前端面试必备》 、《2024面试高频手撕题》 &#x1f35a; 蓝桥云课签约作者、上架课程《Vue.js 和 E…

【AcWing】蓝桥杯集训每日一题Day26|分解质因数|试除法|3377.约数的个数(C++)

3377.约数的个数 3377. 约数的个数 - AcWing题库难度&#xff1a;简单时/空限制&#xff1a;1s / 64MB总通过数&#xff1a;3529总尝试数&#xff1a;6834来源&#xff1a;清华大学考研机试题算法标签数学知识约数试除法因式分解 题目内容 输入 n 个整数&#xff0c;依次输出…

Ceph学习 -8.认证管理-用户基础

文章目录 1.用户基础1.1 基础知识1.2 简单实践1.3 小结 1.用户基础 学习目标&#xff1a;这一节&#xff0c;我们从基础知识、简单实践、小结三个方面来学习。 1.1 基础知识 简介 Ceph集群管理员能够直接在Ceph集群中创建、更新和删除用户 注意&#xff1a;创建用户时&#x…

计算机网络知识等汇总补充

计算机网络知识汇总补充 一、四次挥手1、为什么TCP要等待2MSL2、如果说一个系统中&#xff0c;有大量的time_wait和close_wait&#xff0c;会是什么原因&#xff1f; 二、你是怎么解决粘包问题&#xff1f;三、你觉得哪些场景适合redis四、redis的持久化策略五、你会怎么保证my…

4-云原生监控体系-Grafana-基本使用

1. 介绍 使用Grafana&#xff0c;您可以通过漂亮、灵活的仪表板创建、探索和共享所有数据。查询、可视化、提醒和理解您的数据&#xff0c;无论数据存储在何处。 图片出处&#xff1a; https://grafana.com/grafana/ 官方网站 2. 界面介绍 Connections 可以配置数据源&#x…

自动驾驶感知场景挖掘

目录 前言 1. 目标检测与跟踪 2. 语义分割 3. 环境建模 4. 场景理解与预测 5. 异常检测与处理 总结 前言 自动驾驶感知场景挖掘是指利用传感器和算法技术&#xff0c;对车辆周围的环境进行实时监测和理解。这种技术可以识别和分析道路、车辆、行人、交通标志等各种元素…

php-redis windows ,pecl 已经不维护了,解决方案:php 8.2 | 8.3+ redis extension windows

从论坛上pecl 已经不维护了&#xff0c;直接让大家到ci 去下载 https://stackoverflow.com/questions/76496488/redis-dll-not-found-for-php8-2/76496489#76496489 让我们找最新的一次commit &#xff0c;然后又action 构建&#xff0c;再下载&#xff0c;这样的话也好&#…

Redis从入门到精通(十三)Redis分布式缓存(一)RDB和AOF持久化、Redis主从集群的搭建与原理分析

文章目录 第5章 Redis分布式缓存5.1 Redis持久化5.1.1 RDB持久化5.1.1.1 执行时机5.1.1.2 bgsave原理 5.1.2 AOF持久化5.1.2.1 AOF原理5.1.2.2 AOF配置5.1.2.3 AOF文件重写 5.1.3 RDB和AOF的对比 5.2 Redis主从5.2.1 搭建主从结构5.2.2 主从数据同步原理5.2.2.1 全量同步5.2.2.…

集群开发学习(一)(安装GO和MySQL,K8S基础概念)

完成gin小任务 参考文档&#xff1a; https://www.kancloud.cn/jiajunxi/ginweb100/1801414 https://github.com/hanjialeOK/going 最终代码地址&#xff1a;https://github.com/qinliangql/gin_mini_test.git 学习 1.安装go wget https://dl.google.com/go/go1.20.2.linu…

【Ubuntu】 Github Readme导入GIF

1.工具安装 我们使用 ffmpeg 软件来完成转换工作1.1 安装命令 sudo add-apt-repository ppa:jonathonf/ffmpeg-3sudo apt-get updatesudo apt-get install ffmpeg1.2 转换命令 &#xff08;1&#xff09;直接转换命令&#xff1a; ffmpeg -i out.mp4 out.gif(2) 带参数命令&…

泛微E-Cology ProcessOverRequestByXml 任意文件读取漏洞复现

0x01 产品简介 泛微协同管理应用平台E-Cology是一套兼具企业信息门户、知识文档管理、工作流程管理、人力资源管理、客户关系管理、项目管理、财务管理、资产管理、供应链管理、数据中心功能的企业大型协同管理平台。 0x02 漏洞概述 泛微e-cology某处功能点最初针对用户输入…

【洛谷 P4017】最大食物链计数 题解(深度优先搜索+动态规划+邻接表+记忆化搜索+剪枝)

最大食物链计数 题目背景 你知道食物链吗&#xff1f;Delia 生物考试的时候&#xff0c;数食物链条数的题目全都错了&#xff0c;因为她总是重复数了几条或漏掉了几条。于是她来就来求助你&#xff0c;然而你也不会啊&#xff01;写一个程序来帮帮她吧。 题目描述 给你一个…

K8S之资源管理

关于资源管理&#xff0c;我们会从计算机资源管理&#xff08;Computer Resources&#xff09;、服务质量管理&#xff08;Qos&#xff09;、资源配额管理&#xff08;LimitRange、ResourceQuota&#xff09;等方面来进行说明 Kubernetes集群里的节点提供的资源主要是计算机资源…