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

proto: optimize global (un)marshal lock using RWMutex #655

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions proto/table_marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ type marshalElemInfo struct {

var (
marshalInfoMap = map[reflect.Type]*marshalInfo{}
marshalInfoLock sync.Mutex
marshalInfoLock sync.RWMutex

uint8SliceType = reflect.TypeOf(([]uint8)(nil)).Kind()
)
Expand All @@ -105,8 +105,14 @@ var (
// The info it returns may not necessarily initialized.
// t is the type of the message (NOT the pointer to it).
func getMarshalInfo(t reflect.Type) *marshalInfo {
marshalInfoLock.Lock()
marshalInfoLock.RLock()
u, ok := marshalInfoMap[t]
marshalInfoLock.RUnlock()
if ok {
return u
}
marshalInfoLock.Lock()
u, ok = marshalInfoMap[t]
if !ok {
u = &marshalInfo{typ: t}
marshalInfoMap[t] = u
Expand Down
13 changes: 10 additions & 3 deletions proto/table_unmarshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ type unmarshalFieldInfo struct {

var (
unmarshalInfoMap = map[reflect.Type]*unmarshalInfo{}
unmarshalInfoLock sync.Mutex
unmarshalInfoLock sync.RWMutex
)

// getUnmarshalInfo returns the data structure which can be
Expand All @@ -116,10 +116,17 @@ func getUnmarshalInfo(t reflect.Type) *unmarshalInfo {
// unconditionally. We would end up allocating one
// per occurrence of that type as a message or submessage.
// We use a cache here just to reduce memory usage.
unmarshalInfoLock.RLock()
u, ok := unmarshalInfoMap[t]
unmarshalInfoLock.RUnlock()
if ok {
return u
}

unmarshalInfoLock.Lock()
defer unmarshalInfoLock.Unlock()
u := unmarshalInfoMap[t]
if u == nil {
u, ok = unmarshalInfoMap[t]
if !ok {
u = &unmarshalInfo{typ: t}
// Note: we just set the type here. The rest of the fields
// will be initialized on first use.
Expand Down