当前位置:网站首页>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 .
 Read new technology

原网站

版权声明
本文为[yue_ xin_ tech]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231438380940.html