I am curious if the context cancel code is running, such as running until
func Test(ctx context.Context){
c,err := test.test() //if context cancel occur in here
if err != nil{ //this code will be go on ?
return nil, fmt.Errorf("test fail", err)
c2,err := test.test2(ctx)
if err2 != nil{
return nil, fmt.Errorf("test2 fail", err)
}
// this code will run?
println("over!")
}
I checked the context document, but I’m not sure what the situation is like.Will he end immediately or will he run a piece of code?
It doesn’t look like you have any code using ctx, so there can’t be interference.
it means if the "context cancel " occur , the code will go on. If this function is already stuck, it will complete the process in the function, but it will return a context cancel error as long as the function uses the variable declared in context?
If you simply think of ctx as a channel, it is easy to understand. If your code does not monitor ctx status changes, there will be no stop logic.
It is not like Kotlin’s launch.
Ctx is an experience integration tool. Before the emergence of ctx, developers often worried about how to interrupt business processing (such as timeout, cancellation).
After the emergence of ctx, basically newer libraries can see the use of ctx to control business processing. (Even in my opinion, if a tool library does not provide ctx control methods, then this tool library is very bad)
If you look at the implementation of the standard library of ctx, you will find that the logic is very simple. (The premise is that you are willing to read the source code)
1 Like
The simplest way to monitor:
<-ctx.Done()
or
if ctx.Err()!=nil{ return }
other …
If there is no processing logic in the code, it will not stop, for example:
for{
// do work…
}
But if there is logic to process ctx:
for ctx.Err()==nil{
}
Thanks , I misunderstood while reading the document. At first, I thought context was something that manages the lifecycle of a coroutine. 
Golang does not have a way to manage lifecycles (unless it ends its own life).
Of course, this is based on native interfaces.
If you modify the runtime library, or map it through C, you can also “cleverly” end the coroutine from the outside.
Thank you, but it may be a bit difficult for me.