Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. package lockdict
  2.  
  3. import (
  4. "github.com/sargun/goconcurrency/types"
  5. "sync"
  6. )
  7.  
  8. var _ types.ConcurrentDict = (*LockDict)(nil)
  9.  
  10. func NewLockDict() *LockDict {
  11. return &LockDict{
  12. dict: make(map[string]string),
  13. lock: sync.RWMutex{},
  14. }
  15. }
  16.  
  17. type LockDict struct {
  18. dict map[string]string
  19. lock sync.RWMutex
  20. }
  21.  
  22. func (dict *LockDict) SetVal(key, val string) {
  23. dict.lock.Lock()
  24. defer dict.lock.Unlock()
  25. dict.dict[key] = val
  26. }
  27. func (dict *LockDict) CasVal(key, oldVal, newVal string, setOnNotExists bool) bool {
  28. dict.lock.Lock()
  29. defer dict.lock.Unlock()
  30. if val, exists := dict.dict[key]; exists && val == oldVal {
  31. dict.dict[key] = newVal
  32. return true
  33. } else if !exists && setOnNotExists {
  34. dict.dict[key] = newVal
  35. return true
  36. }
  37.  
  38. return false
  39. }
  40. func (dict *LockDict) ReadVal(key string) (string, bool) {
  41.  
  42. dict.lock.RLock()
  43. defer dict.lock.RUnlock()
  44. val, exists := dict.dict[key]
  45. return val, exists
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement