Skip to content

Instantly share code, notes, and snippets.

@phuctm97
Created October 1, 2019 15:40
Show Gist options
  • Save phuctm97/9a9ca46badd87e16b6cdaf899db83cdf to your computer and use it in GitHub Desktop.
Save phuctm97/9a9ca46badd87e16b6cdaf899db83cdf to your computer and use it in GitHub Desktop.
Concurrent-safe value in Go
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment