Original: https://gocn.io/article/373
After GO1.7, the Context.context package was added to achieve goroutine management.
The context basic usage reference Golang uses context to manage the associated goroutine.
In fact, the context also has a very important role, is to set the timeout. For example, if we have an API that is designed like this:
Type Packet interface {
encoding. Binarymarshaler
encoding. Binaryunmarshaler
}
type Stack struct {
}
func (v *stack) Read (CTX context. Context) (PKT Packet, err error) {
return
}
The general use is to use this, create the context and then call the interface:
Ctx,cancel: = Context. Withcancel (context. Background ())
stack: = &stack{}
pkt,err: = stack. Read (CTX)
Then, it can support the cancellation and timeout itself, that is, if the user needs to cancel, such as sending a SIGINT signal, the program needs to exit, you can call cancel after receiving the signal:
SC: = Make (chan os. Signal, 0)
Signal. Notify (SC, syscall. SIGINT, Syscall. SIGTERM)
go func () {for
range sc {
cancel ()
}
} ()
If you need to time out, this API does not change, only need to set the time-out before the call:
Ctx,cancel: = Context. Withtimeout (context. Background (), 3*time. Second)
defer cancel ()
pkt,err: = stack. Read (CTX)
If a program is running, like read waiting, then you should run it yourself without human intervention. and manual intervention, that is, need to cancel, such as to upgrade the program, or need to stop the service, all belong to this cancellation operation. And time-out, is generally the system's strategy, because can not be kept waiting, it is necessary to stop the service at a certain time without response. In fact, the context of these two can support very well, and does not affect the logic of read itself, in read only need to focus on the context is done:
Func (v *stack) Read (CTX context. Context) (PKT Packet, err Error) {
Select {
//Case <-Datachannel://Parse Packet from data channel.
Case <-CTX. Done ():
return nil,ctx. ERR ()
}
return
}
This is why the context is accepted as the standard library of the package, it is very powerful and useful, but very simple. A line of context, deep work and name.
In addition, context can also be passed Key-value objects, such as we want in the log, the relevant goroutine all print a simplified CID, then you can use the context. Withvalue, refer to Go-oryx-lib/logger.