Skip to content

Commit

Permalink
chore(performance): remove Mutex lock in context key
Browse files Browse the repository at this point in the history
See the report: #2350
  • Loading branch information
appleboy committed May 3, 2020
1 parent 4427ca4 commit d5a42fc
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 18 deletions.
17 changes: 0 additions & 17 deletions context.go
Expand Up @@ -16,7 +16,6 @@ import (
"net/url"
"os"
"strings"
"sync"
"time"

"github.com/gin-contrib/sse"
Expand Down Expand Up @@ -53,9 +52,6 @@ type Context struct {

engine *Engine

// This mutex protect Keys map
KeysMutex *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 +82,6 @@ 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 Down Expand Up @@ -228,29 +223,17 @@ 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()
if c.Keys == nil {
c.Keys = make(map[string]interface{})
}

c.Keys[key] = value
c.KeysMutex.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()
value, exists = c.Keys[key]
c.KeysMutex.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

0 comments on commit d5a42fc

Please sign in to comment.