Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package syncval
- import "sync"
- // SyncValue is like a Go interface{} but is safe for concurrent use by multiple goroutines
- // without additional locking or coordination.
- type SyncValue struct {
- mutex *sync.RWMutex
- val interface{}
- }
- // NewSyncValue creates a new sync value.
- func NewSyncValue(v interface{}) *SyncValue {
- return &SyncValue{&sync.RWMutex{}, v}
- }
- // Set sets the value.
- func (t *SyncValue) Set(v interface{}) {
- // Lock locks for writing.
- t.mutex.Lock()
- defer t.mutex.Unlock()
- // Set the value.
- t.val = v
- }
- // Get returns the value.
- func (t *SyncValue) Get() interface{} {
- // Lock locks for reading.
- t.mutex.RLock()
- defer t.mutex.RUnlock()
- // Return the value.
- return t.val
- }
- // Int returns the value as int.
- func (t *SyncValue) Int() int {
- return t.Get().(int)
- }
- // Bool returns the value as bool.
- func (t *SyncValue) Bool() bool {
- return t.Get().(bool)
- }
- // String returns the value as string.
- func (t *SyncValue) String() string {
- return t.Get().(string)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement