Advertisement
Guest User

Untitled

a guest
Aug 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. package chandict
  2.  
  3. import "github.com/sargun/goconcurrency/types"
  4.  
  5. var _ types.ConcurrentDict = (*ChanDict)(nil)
  6.  
  7. type readRequestResponse struct {
  8. val string
  9. exists bool
  10. }
  11.  
  12. type readRequest struct {
  13. readKey string
  14. responseChan chan readRequestResponse
  15. }
  16.  
  17. type writeRequest struct {
  18. readKey string
  19. writeVal string
  20. responseChan chan struct{}
  21. }
  22.  
  23. type casRequest struct {
  24. setOnNotExists bool
  25. readKey string
  26. oldVal string
  27. newVal string
  28. responseChan chan bool
  29. }
  30.  
  31. type ChanDict struct {
  32. dict map[string]string
  33. readRequests chan readRequest
  34. writeRequests chan writeRequest
  35. casRequests chan casRequest
  36. }
  37.  
  38. func NewChanDict() *ChanDict {
  39. d := &ChanDict{
  40. dict: make(map[string]string),
  41. readRequests: make(chan readRequest),
  42. writeRequests: make(chan writeRequest),
  43. casRequests: make(chan casRequest),
  44. }
  45. go d.run()
  46. return d
  47. }
  48.  
  49. func (dict *ChanDict) run() {
  50. for {
  51. select {
  52. case wr := <-dict.writeRequests:
  53. dict.dict[wr.readKey] = wr.writeVal
  54. wr.responseChan <- struct{}{}
  55. case rr := <-dict.readRequests:
  56. val, exists := dict.dict[rr.readKey]
  57. rr.responseChan <- readRequestResponse{val, exists}
  58. case cr := <-dict.casRequests:
  59. if val, exists := dict.dict[cr.readKey]; exists && val == cr.oldVal {
  60. dict.dict[cr.readKey] = cr.newVal
  61.  
  62. cr.responseChan <- true
  63. } else if !exists && cr.setOnNotExists {
  64. dict.dict[cr.readKey] = cr.newVal
  65. cr.responseChan <- true
  66. } else {
  67. cr.responseChan <- false
  68.  
  69. }
  70.  
  71. }
  72. }
  73. }
  74.  
  75. func (dict *ChanDict) SetVal(key, val string) {
  76. c := make(chan struct{})
  77. w := writeRequest{readKey: key, writeVal: val, responseChan: c}
  78. dict.writeRequests <- w
  79. <-c
  80. }
  81.  
  82. func (dict *ChanDict) ReadVal(key string) (string, bool) {
  83. c := make(chan readRequestResponse)
  84. w := readRequest{readKey: key, responseChan: c}
  85. dict.readRequests <- w
  86. resp := <-c
  87. return resp.val, resp.exists
  88. }
  89.  
  90. func (dict *ChanDict) CasVal(key, oldVal, newVal string, setOnNotExists bool) bool {
  91. c := make(chan bool)
  92. w := casRequest{readKey: key, oldVal: oldVal, newVal: newVal, responseChan: c, setOnNotExists: setOnNotExists}
  93. dict.casRequests <- w
  94. return <-c
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement