Does this make sense with defer cancel() ?

王林
Release: 2024-02-12 13:45:06
forward
859 people have browsed it

这对于 defer cancel() 有意义吗?

Question content

In http.HandlerFunc I got this. But my question is: does it make sense to put defer cancel() after applying the timeout context?

Because the bottom selection will continue to listen until the context is completed. And the delay will be executed after the context is completed. But is that done? :)

//  Apply timeout context
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Duration(time.Duration(match_route.timeout) * time.Second))
defer cancel() // <--- does this make sense

go func(){
    match_route.handler(w, r.WithContext(ctx))
    cancel()
}()

select {
case <-ctx.Done():
    if ctx.Err() == context.DeadlineExceeded {
        http.Error(w, "Timeout", http.StatusRequestTimeout)
    }
}
Copy after login

Solution

Yes, I think this does make sense, in fact the purpose of using defer cancel() is to ensure that the cancel function is called to release the context associated with it resource, no matter how the function exits, in your example the cancel() function is deferred until http.HandlerFunc completes or when the context completes, so go func () is responsible for executing the match_route.handler function using the provided context, and then calling cancel() to explicitly cancel the context, and the select statement is used to wait for the context Complete, if the context is completed because the deadline is exceeded, an error response is returned!

The above is the detailed content of Does this make sense with defer cancel() ?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!