改进gtype锁机制

This commit is contained in:
john
2018-09-10 18:09:13 +08:00
parent 6e2926d5f9
commit 35a7cb361d
2 changed files with 26 additions and 24 deletions

View File

@ -7,17 +7,18 @@
package gtype
import (
"sync/atomic"
"sync"
)
type Bytes struct {
val atomic.Value
mu sync.RWMutex
val []byte
}
func NewBytes(value...[]byte) *Bytes {
t := &Bytes{}
if len(value) > 0 && value[0] != nil{
t.val.Store(value[0])
if len(value) > 0 {
t.val = value[0]
}
return t
}
@ -27,16 +28,14 @@ func (t *Bytes) Clone() *Bytes {
}
func (t *Bytes) Set(value []byte) {
if value == nil {
return
}
t.val.Store(value)
t.mu.Lock()
t.val = value
t.mu.Unlock()
}
func (t *Bytes) Val() []byte {
v := t.val.Load()
if v != nil {
return v.([]byte)
}
return nil
t.mu.RLock()
b := t.val
t.mu.RUnlock()
return b
}

View File

@ -7,19 +7,19 @@
package gtype
import (
"sync/atomic"
"sync"
)
type String struct {
val atomic.Value
mu sync.RWMutex
val string
}
func NewString(value...string) *String {
t := &String{}
if len(value) > 0 {
t.val.Store(value[0])
return &String{val:value[0]}
}
return t
return &String{}
}
func (t *String) Clone() *String {
@ -27,13 +27,16 @@ func (t *String) Clone() *String {
}
func (t *String) Set(value string) {
t.val.Store(value)
t.mu.Lock()
t.val = value
t.mu.Unlock()
}
func (t *String) Val() string {
v := t.val.Load()
if v != nil {
return v.(string)
}
return ""
t.mu.RLock()
s := t.val
t.mu.RUnlock()
return s
}