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!
version 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!