diff --git a/g/container/gtype/bytes.go b/g/container/gtype/bytes.go index a7cc89e86..fb067de5d 100644 --- a/g/container/gtype/bytes.go +++ b/g/container/gtype/bytes.go @@ -6,19 +6,16 @@ package gtype -import ( - "sync" -) +import "sync/atomic" type Bytes struct { - mu sync.RWMutex - val []byte + val atomic.Value } func NewBytes(value...[]byte) *Bytes { t := &Bytes{} if len(value) > 0 { - t.val = value[0] + t.val.Store(value[0]) } return t } @@ -28,14 +25,13 @@ func (t *Bytes) Clone() *Bytes { } func (t *Bytes) Set(value []byte) { - t.mu.Lock() - t.val = value - t.mu.Unlock() + t.val.Store(value) } func (t *Bytes) Val() []byte { - t.mu.RLock() - b := t.val - t.mu.RUnlock() - return b + s := t.val.Load() + if s != nil { + return s.([]byte) + } + return nil } diff --git a/g/container/gtype/gtype_test.go b/g/container/gtype/gtype_test.go index 1e79d19ee..736d064e5 100644 --- a/g/container/gtype/gtype_test.go +++ b/g/container/gtype/gtype_test.go @@ -197,13 +197,13 @@ func BenchmarkInterface_Val(b *testing.B) { } -func BenchmarkAtomicString_Store(b *testing.B) { +func BenchmarkAtomicValue_Store(b *testing.B) { for i := 0; i < b.N; i++ { at.Store(i) } } -func BenchmarkAtomicString_Load(b *testing.B) { +func BenchmarkAtomicValue_Load(b *testing.B) { for i := 0; i < b.N; i++ { at.Load() } diff --git a/g/container/gtype/string.go b/g/container/gtype/string.go index 998f38c8a..ede15a093 100644 --- a/g/container/gtype/string.go +++ b/g/container/gtype/string.go @@ -7,19 +7,19 @@ package gtype import ( - "sync" + "sync/atomic" ) type String struct { - mu sync.RWMutex - val string + val atomic.Value } func NewString(value...string) *String { + t := &String{} if len(value) > 0 { - return &String{val:value[0]} + t.val.Store(value[0]) } - return &String{} + return t } func (t *String) Clone() *String { @@ -27,16 +27,15 @@ func (t *String) Clone() *String { } func (t *String) Set(value string) { - t.mu.Lock() - t.val = value - t.mu.Unlock() + t.val.Store(value) } func (t *String) Val() string { - t.mu.RLock() - s := t.val - t.mu.RUnlock() - return s + s := t.val.Load() + if s != nil { + return s.(string) + } + return "" }