Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(performance): Change *sync.RWMutex to sync.RWMutex #2351

Merged
merged 3 commits into from May 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 12 additions & 15 deletions context.go
Expand Up @@ -54,7 +54,7 @@ type Context struct {
engine *Engine

// This mutex protect Keys map
KeysMutex *sync.RWMutex
mu sync.RWMutex

// Keys is a key/value pair exclusively for the context of each request.
Keys map[string]interface{}
Expand Down Expand Up @@ -86,7 +86,7 @@ func (c *Context) reset() {
c.Params = c.Params[0:0]
c.handlers = nil
c.index = -1
c.KeysMutex = &sync.RWMutex{}

c.fullPath = ""
c.Keys = nil
c.Errors = c.Errors[0:0]
Expand All @@ -98,7 +98,12 @@ func (c *Context) reset() {
// 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.
func (c *Context) Copy() *Context {
var cp = *c
cp := Context{
writermem: c.writermem,
Request: c.Request,
Params: c.Params,
engine: c.engine,
}
cp.writermem.ResponseWriter = nil
cp.Writer = &cp.writermem
cp.index = abortIndex
Expand Down Expand Up @@ -228,29 +233,21 @@ func (c *Context) Error(err error) *Error {
// Set is used to store a new key/value pair exclusively for this context.
// It also lazy initializes c.Keys if it was not used previously.
func (c *Context) Set(key string, value interface{}) {
if c.KeysMutex == nil {
c.KeysMutex = &sync.RWMutex{}
}

c.KeysMutex.Lock()
c.mu.Lock()
if c.Keys == nil {
c.Keys = make(map[string]interface{})
}

c.Keys[key] = value
c.KeysMutex.Unlock()
c.mu.Unlock()
}

// Get returns the value for the given key, ie: (value, true).
// If the value does not exists it returns (nil, false)
func (c *Context) Get(key string) (value interface{}, exists bool) {
if c.KeysMutex == nil {
c.KeysMutex = &sync.RWMutex{}
}

c.KeysMutex.RLock()
c.mu.RLock()
value, exists = c.Keys[key]
c.KeysMutex.RUnlock()
c.mu.RUnlock()
return
}

Expand Down
2 changes: 1 addition & 1 deletion gin.go
Expand Up @@ -162,7 +162,7 @@ func Default() *Engine {
}

func (engine *Engine) allocateContext() *Context {
return &Context{engine: engine, KeysMutex: &sync.RWMutex{}}
return &Context{engine: engine}
}

// Delims sets template left and right delims and returns a Engine instance.
Expand Down