What is the context
Context is a structure unique to the Go language. It is not easy to use examples of other languages’ types. Specific functions need to be represented by examples
The channel and the select
Before you understand how to use context, you need to understand the use of channel and select. I won’t go into the details here
channel
Channels, similar to blocking queues in Java, are an elegant thread-safe tool
If you want to understand his principle, you can see the detailed explanation I posted earlier channel
Juejin. Cn/post / 697140…
select
Select is also unique to Go. It works like switch, but its input value can only be channel. If there is no channel to operate on, it will be blocked, and if there is, it will run in case. If more than one channel can be operated on, one is randomly selected and run. If there is a default method, it will call the default method directly, even if there is no channel to operate on and it will not block.
The sample
First of all, the coroutine does not terminate until its instructions are executed. In other words, if you write an infinite loop, the coroutine will keep running by itself. So if you want to terminate coroutines, there are three ways
- Using global variables
- Use select, channel
- Use the context
Global variables are the easiest way to think about it, but the problem with this approach is that it has thread-safety issues, so locks are needed.
Use select, channel
func recycle(c <-chan int) {
for true {
select {
case <-c:
fmt.Println("a")
default:
fmt.Println("In circulation")}}}Copy the code
More elegant than global variables, can be used for fewer coroutines. But if coroutines are nested or have many layers of coroutines, the relationship can be complicated.
So the most elegant way to do this is to use the context, and that leads to one of its features, which is that it can do signaling, and it can do upstream unsignaling, and downstream tasks undoing themselves
function
- Pass the key value
- Timeout control
- Active de-control
Context is a tree structure, and when you control a node, it means that its children are also controlled.
For example, if a service call timed out, it should return failed data, but the child coroutine is still running. This is not necessary. Context can be used to prevent the child coroutine from running.
Method of use
Visually, think of the Context as a river flowing through your program, and every method argument must start with a Context