当前位置:网站首页>Important knowledge of golang: detailed explanation of context
Important knowledge of golang: detailed explanation of context
2022-06-23 15:25:00 【yue_ xin_ tech】
Abstract
In a lot of Go In the open source framework , We often see context The figure of , There are many usage scenarios , Like timeout notification , Cancellation notices use context. Today, let's get to know it well , have a look context Relevant knowledge and underlying principles .
context Introduce
context It can be seen from its literal size , It's used to convey information . Of course , This kind of transfer is not just to stuff the data to the callee , It can also carry out chain transmission , By saving father and son context Relationship , Iterate continuously to get data .
besides ,context It can also spread in a chain channel The signal .
We know channel Is used to do goroutine Used for communication . This makes goroutine Chain signal notification can be carried out between , So as to achieve a top-down effect .
For example, notify all people with context Yes “ blood kinship ” Relational goroutine Cancel .
Context Interface
stay Go It does not directly provide us with a unified context object , Instead, an interface type is designed Context. Then several specific types of interfaces are implemented on these interfaces context.
The advantage is that we only need to define according to the open interface , Can also achieve their own context, And then talk to the official context Used together .
In analyzing several official context Before , Let's take a look first context Several interfaces required to be implemented :
- Deadline() (deadline time.Time, ok bool)
- Done() <-chan struct{}
- Err() error
- Value(key interface{}) interface{}
among :
Deadline() If there is a deadline , You have to return the corresponding deadline Time ; without , be ok The value of is false.
Done() About channel The data communication of , And its data type is struct{}, An empty structure , So in Go It's all straight through close channel For notification , No specific data transmission will be involved .
Err() An error is returned error, If the top Done() Of channel Not by close, be error by nil; If channel Has been close, be error Will return close Why , Such as timeout or manual cancellation .
Value Is the method used to store specific data .
Context type
Simply read Context After the interface , Let's take a look at the official context type . There are mainly four kinds of , Namely emptyCtx,cancelCtx,timerCtx,valueCtx:
- emptyCtx: Empty context, The above 4 Interface , But it's all direct return The default value is , No specific function code .
- cancelCtx: Used to cancel the notice context
- timerCtx: For timeout notification context
- valueCtx: Used to transmit value context
among :
emptyCtx It means a useless context, Generally used as the initial context, As a father context Use . And what we often see is context.Background() Back to you emptyCtx.
Other types of creation methods are as follows :
- WithCancel Method creates cancelCtx Type of context.
- WithDeadline Method creates timerCtx Type of context.
- WithValue Method creates valueCtx Type of context.
When creating the above three methods, it will be required to pass parent context Come in , To achieve Chain transmission The purpose of information .
Context Source code
context The source code is src/context/context.go in , I believe you will study it carefully , You can also see some of the above context object . Here's a brief explanation cancelCtx、timerCtx、valueCtx The core process of .
1)cancelCtx 、timerCtx( For notification context)
cancelCtx 、timerCtx When created, it will call propagateCancel Method , Change the current context Hang on Father context Next .
And then Done() Method returns the corresponding channel, Enables the caller to monitor channel The signal .
When it comes to execution Cancel action when , Will pass cancel Method close channel, In order to achieve notice goroutine Purpose .
stay channel Closing will also affect Son context call cancel Method , Until there are no children context.
cancelCtx and timerCtxt The difference is cancelCtx yes Manual call cancel Method to trigger a cancellation notification ;
and timerCtxt Through AfterFunc Timeout to Automatic triggering cancel Method .
2)valueCtx( Used to transmit value context)
valueCtx adopt key-value Form to store data , When you can't find it key when , It will come to Father context Search in , Until there is no father context:
func (c *valueCtx) Value(key interface{
}) interface{
} {
if c.key == key {
return c.val
}
return c.Context.Value(key) // To the father context Search in
}
context matters needing attention
Finally, let's look at using context A few precautions when :
- context Of Done() Methods often require cooperation select {} Use , Exit by listening .
- Try to expose... Through function parameters context, Don't include it in a custom structure .
- WithValue Type of context Try to store some global data, Instead of storing some dispensable parts data.
- context It's concurrent security .
- once context Perform the cancel action , All derived context Will trigger cancellation .
Interested friends can search the official account 「 Read new technology 」, Pay attention to more push articles .
If you can , Just like it by the way 、 Leave a message 、 Under the share , Thank you for your support !
Read new technology , Read more new knowledge .
边栏推荐
- 他山之石 | 微信搜一搜中的智能问答技术
- Volatile~ variables are not visible under multithreading
- [pyside2] pyside2 window is on the top of Maya (note)
- List query sorting parameter processing
- 《墨者学院——SQL手工注入漏洞测试(MySQL数据库)》
- 力扣解法匯總513-找樹左下角的值
- Top 10 purchase, sales and inventory software rankings!
- RF analyzer demo setup
- 山东:美食“隐藏款”,消费“扫地僧”
- 2021-05-08
猜你喜欢

Un million de bonus vous attend, le premier concours d'innovation et d'application de la Chine Yuan cosmique Joint Venture Black Horse Hot Recruitment!

Starting from 3, add paging function in the business system
Explain in detail the principle and implementation of redis distributed lock

Raspberry PI installing the wiring pi

js中的push函数介绍
Redis缓存三大异常的处理方案梳理总结
![[datahub] LinkedIn datahub learning notes](/img/ca/9c4a87d38155edd093cbb81d81ee81.png)
[datahub] LinkedIn datahub learning notes

JS create an array (literal)

2021-04-15

百萬獎金等你來拿,首届中國元宇宙創新應用大賽聯合創業黑馬火熱招募中!
随机推荐
Idea view View the class file idea Class folder
RF analyzer demo setup
golang 重要知识:sync.Cond 机制
An idea plug-in for automatically generating unit tests
Analysis of graphical level-1 programming problem of Electronic Society: cat and mouse
基因检测,如何帮助患者对抗疾病?
Sfod: passive domain adaptation and upgrade optimization, making the detection model easier to adapt to new data (attached with paper Download)
操作系统底层知识总结(面试)
AI intelligent robot saves us time and effort
Mysql双主配置的详细步骤
PHP 2D array insert
Golang-- judge whether the strings are equal
The new version of Alibaba Seata finally solves the idempotence, suspension and empty rollback problems of the TCC mode
2021-06-07
golang 重要知识:RWMutex 读写锁分析
Jsr303 data verification
嵌入式软件架构设计-程序分层
The "shoulder" of sales and service in the heavy truck industry, Linyi Guangshun deep ploughing product life cycle service
进销存软件排行榜前十名!
JS垃圾回收