惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

罗磊的独立博客
Cisco Talos Blog
Cisco Talos Blog
C
Check Point Blog
博客园_首页
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Martin Fowler
Martin Fowler
Recorded Future
Recorded Future
S
Security @ Cisco Blogs
L
LINUX DO - 最新话题
博客园 - 司徒正美
P
Privacy International News Feed
G
Google Developers Blog
I
Intezer
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
C
Cybersecurity and Infrastructure Security Agency CISA
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Scott Helme
Scott Helme
K
Kaspersky official blog
I
InfoQ
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Webroot Blog
Webroot Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
大猫的无限游戏
大猫的无限游戏
D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
Microsoft Azure Blog
Microsoft Azure Blog
Spread Privacy
Spread Privacy
量子位
H
Hacker News: Front Page
Simon Willison's Weblog
Simon Willison's Weblog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
SecWiki News
SecWiki News
S
Security Affairs
Latest news
Latest news
人人都是产品经理
人人都是产品经理
C
CERT Recently Published Vulnerability Notes
S
Security Archives - TechRepublic
V
Visual Studio Blog
T
Troy Hunt's Blog
S
Secure Thoughts
F
Fortinet All Blogs
V
V2EX
The Register - Security
The Register - Security
J
Java Code Geeks
MongoDB | Blog
MongoDB | Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - 海风吹

Chrome浏览器界面截图 linux文件锁flock【转】 go的临时对象池--sync.Pool golang 小知识-持续更新中 【转】Go Channels Golang文件名命名规则 Parquet存储格式 - 论文翻译【转】 预装的Office2016,文件图标表显示以及新建失败问题解决 方法 Gamma编码及Delta编码概述 时序数据库技术体系 – InfluxDB 多维查询之倒排索引 时序数据库技术体系 – InfluxDB TSM存储引擎之TSMFile 时间序列数据的存储和计算 - 开源时序数据库解析 时序数据库技术体系-时序数据存储模型设计 时序数据库-为万物互联插上一双翅膀 JMS和ActiveMQ的关系 JMS(Java消息服务)入门教程 Influxdb时序数据库阅读笔记 代码只是事业的 5%,程序员创业注意事项 golang 之 channel
golang中context包学习
海风吹 · 2017-05-14 · via 博客园 - 海风吹
  • 摘要

go语言中goroutine之间的关联关系,缺乏维护,在erlang中有专门的机制来保障新开仟程的生命周期,

在go语言中,只能通过channel + select来实现,但不够直观,感觉很绕。

Context 通常被译作 上下文 ,它是一个比较抽象的概念。在公司技术讨论时也经常会提到 上下文 。一般理解为程序单元的一个运行状态、现场、快照,而翻译中 上下 又很好地诠释了其本质,上下上下则是存在上下层的传递,  会把内容传递给  。在Go语言中,程序单元也就指的是Goroutine。

context 包不仅实现了在程序单元之间共享状态变量的方法,同时能通过简单的方法,使我们在被调用程序单元的外部,通过设置ctx变量值,将过期或撤销这些信号传递给被调用的程序单元。

  • 源码剖析

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。