Home >Backend Development >Golang >Detailed explanation of Golang context
The following column golang tutorial will explain the context of Golang in detail. I hope it will be helpful to friends in need!
#PrefaceYes, today I originally wanted to go out and play. I bought a train ticket and overslept again. . There is no way, maybe it is God's will, so I have to summarize the context of golang, hoping to make a break with the context. In the company, when we write various services, we must use Context as the first parameter. At first, I thought it was mainly used for full-link troubleshooting and tracking. But with more contact, it turns out it's more than that. Text1.Detailed explanation of context1.1 Generation backgroundBefore go 1.7, context was still non-programmed (including golang.org/x /net/context), the golang team found that context is quite easy to use and is used in many places, so they incorporated it into the standard libraryversion 1.7. Common usage postures of context:
1. In web programming, one request corresponds to data interaction between multiple goroutines2. Timeout control
3. Context control
1.2 The underlying structure of context
type Context interface { Deadline() (deadline time.Time, ok bool) Done() <-chan struct{} Err() error Value(key interface{}) interface{} }
Meaning | |
---|---|
Returns a time.Time, indicating the time when the current Context should end, ok means there is an end time | |
A close channel returned when the Context is canceled or times out, telling the context-related functions to stop the current work and return. (This is a bit like global broadcast) | |
The reason why context was canceled | |
The place where context implements shared data storage is coroutine safe (remember what I said before that map is unsafe? So when you encounter the map structure, if it is not sync.Map, you need to lock it to operate) |
// A canceler is a context type that can be canceled directly. The // implementations are *cancelCtx and *timerCtx. type canceler interface { cancel(removeFromParent bool, err error) Done() <-chan struct{} }
Then the library provides 4 Context implementations for everyone to play with
Structure | Function | |
---|---|---|
type emptyCtx int | Completely empty Context, the implemented functions also return nil, It just implements the Context interface | |
type cancelCtx struct { | Context mu sync.Mutex done chan struct{} children map[canceler]struct{} err error } Inherits from Context and also implements the canceler interface |
|
type timerCtx struct { | cancelCtx timer *time.Timer // Under cancelCtx.mu. deadline time.Time } Inherited from | cancelCtx, adding timeout mechanism |
type valueCtx struct { | Context key, val interface{} } Data that stores key-value pairs |
The above is the detailed content of Detailed explanation of Golang context. For more information, please follow other related articles on the PHP Chinese website!