gtype底层统一修改为原子操作

This commit is contained in:
john
2018-09-12 14:02:32 +08:00
parent aebb4d057a
commit d0e86c24b7
3 changed files with 22 additions and 27 deletions

View File

@ -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
}

View File

@ -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()
}

View File

@ -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 ""
}