登录
首页 >  Golang >  Go问答

为什么处理程序内部的 goroutine 需要制作上下文的副本?

来源:stackoverflow

时间:2024-02-06 20:27:23 301浏览 收藏

大家好,今天本人给大家带来文章《为什么处理程序内部的 goroutine 需要制作上下文的副本?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我最近开始用 Go 重写一些 Python 服务以加快速度,并发现了 gin 文档的这一部分: https://github.com/gin-gonic/gin#goroutines-inside-a-middleware

所以我理解了说明,但我试图理解为什么?制作副本的意义是什么?如果我不为处理程序中的 goroutine 制作上下文副本,会带来什么问题?


正确答案


gin-gonic 本身就是异步的,这使得它很棒。 如果您在处理程序中使用并发,那么您很可能会遇到上下文(即 struct )消失的情况

  • 已过时,因为它保存每个请求的数据(参数、受互斥锁保护的密钥)

  • 空,这将导致回退到默认上下文

它的样子是这样的:

type context struct {
writermem responsewriter
request   *http.request
writer    responsewriter

params   params
handlers handlerschain
index    int8
fullpath string

engine       *engine
params       *params
skippednodes *[]skippednode

// this mutex protects keys map.
mu sync.rwmutex

// keys is a key/value pair exclusively for the context of each request.
keys map[string]any

// errors is a list of errors attached to all the handlers/middlewares who used this context.
errors errormsgs

// accepted defines a list of manually accepted formats for content negotiation.
accepted []string

// querycache caches the query result from c.request.url.query().
querycache url.values

// formcache caches c.request.postform, which contains the parsed form data from post, patch,
// or put body parameters.
formcache url.values

// samesite allows a server to define a cookie attribute making it impossible for
// the browser to send this cookie along with cross-site requests.
samesite http.samesite

}

为了预见此类问题和竞争条件 - 当您的处理程序使用 go 并发时,您必须使用 copy

这是来自 gin-gonic 存储库的引用:

// Copy returns a copy of the current context that can be safely used outside the request's scope.
// This has to be used when the context has to be passed to a goroutine.

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>