Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. package syncval
  2.  
  3. import "sync"
  4.  
  5. // SyncValue is like a Go interface{} but is safe for concurrent use by multiple goroutines
  6. // without additional locking or coordination.
  7. type SyncValue struct {
  8. mutex *sync.RWMutex
  9. val interface{}
  10. }
  11.  
  12. // NewSyncValue creates a new sync value.
  13. func NewSyncValue(v interface{}) *SyncValue {
  14. return &SyncValue{&sync.RWMutex{}, v}
  15. }
  16.  
  17. // Set sets the value.
  18. func (t *SyncValue) Set(v interface{}) {
  19. // Lock locks for writing.
  20. t.mutex.Lock()
  21. defer t.mutex.Unlock()
  22.  
  23. // Set the value.
  24. t.val = v
  25. }
  26.  
  27. // Get returns the value.
  28. func (t *SyncValue) Get() interface{} {
  29. // Lock locks for reading.
  30. t.mutex.RLock()
  31. defer t.mutex.RUnlock()
  32.  
  33. // Return the value.
  34. return t.val
  35. }
  36.  
  37. // Int returns the value as int.
  38. func (t *SyncValue) Int() int {
  39. return t.Get().(int)
  40. }
  41.  
  42. // Bool returns the value as bool.
  43. func (t *SyncValue) Bool() bool {
  44. return t.Get().(bool)
  45. }
  46.  
  47. // String returns the value as string.
  48. func (t *SyncValue) String() string {
  49. return t.Get().(string)
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement