2016-03-31 16:57:08 +00:00
|
|
|
package safe
|
|
|
|
|
|
|
|
import (
|
2016-04-13 18:36:23 +00:00
|
|
|
"sync"
|
2016-03-31 16:57:08 +00:00
|
|
|
)
|
|
|
|
|
2016-04-13 18:36:23 +00:00
|
|
|
// Safe contains a thread-safe value
|
|
|
|
type Safe struct {
|
|
|
|
value interface{}
|
|
|
|
lock sync.RWMutex
|
2016-03-31 16:57:08 +00:00
|
|
|
}
|
|
|
|
|
2016-04-13 18:36:23 +00:00
|
|
|
// New create a new Safe instance given a value
|
|
|
|
func New(value interface{}) *Safe {
|
|
|
|
return &Safe{value: value, lock: sync.RWMutex{}}
|
2016-03-31 16:57:08 +00:00
|
|
|
}
|
|
|
|
|
2016-04-13 18:36:23 +00:00
|
|
|
// Get returns the value
|
|
|
|
func (s *Safe) Get() interface{} {
|
|
|
|
s.lock.RLock()
|
|
|
|
defer s.lock.RUnlock()
|
|
|
|
return s.value
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set sets a new value
|
|
|
|
func (s *Safe) Set(value interface{}) {
|
|
|
|
s.lock.Lock()
|
|
|
|
defer s.lock.Unlock()
|
|
|
|
s.value = value
|
2016-03-31 16:57:08 +00:00
|
|
|
}
|