Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "sync"
  6. )
  7.  
  8. type ILibraryState interface {
  9. DoSomething(arg int) error
  10. }
  11.  
  12. type LibraryState struct {
  13. lock *sync.Mutex
  14. // Some private state
  15. }
  16.  
  17. func (l *LibraryState) DoSomething(arg int) error {
  18. // Do some arg check
  19.  
  20. // Transactional synchronisation
  21. l.lock.Lock()
  22. defer l.lock.Unlock()
  23.  
  24. // Do something
  25. fmt.Println("Hello, playground")
  26. return nil;
  27. }
  28.  
  29. func NewLibrary() ILibraryState {
  30. lib := LibraryState{}
  31. lib.lock = &sync.Mutex{}
  32. return &lib
  33. }
  34.  
  35. func main() {
  36. l := NewLibrary()
  37. l.DoSomething(5)
  38. }
  39.  
  40. package main
  41.  
  42. import (
  43. "fmt"
  44. )
  45.  
  46. type ILibraryState interface {
  47. DoSomething(arg int) error
  48. }
  49.  
  50. type LibraryState struct {
  51. command chan (interface{})
  52. response chan (interface{})
  53. // Some private state
  54. }
  55.  
  56. type commandDoSomething struct {
  57. arg int
  58. }
  59.  
  60. func (l *LibraryState) DoSomething(arg int) error {
  61. // Do some arg check
  62.  
  63. // Perform operation transactionally
  64. l.command <- commandDoSomething{arg}
  65. res := <-l.response
  66. if res == nil {
  67. return nil
  68. }
  69. return res.(error)
  70. }
  71.  
  72. func (l *LibraryState) reallyDoSomething(arg int) {
  73. // Do something
  74. fmt.Println("Hello, playground")
  75. var err error = nil
  76. l.response <- err
  77. }
  78.  
  79. func (l *LibraryState) processCommands() {
  80. for {
  81. switch c := (<-l.command).(type) {
  82.  
  83. case commandDoSomething:
  84. l.reallyDoSomething(c.arg)
  85. }
  86. }
  87. }
  88.  
  89. func NewLibrary() ILibraryState {
  90. lib := LibraryState{}
  91. lib.command = make(chan (interface{}))
  92. lib.response = make(chan (interface{}))
  93. go lib.processCommands()
  94. return &lib
  95. }
  96.  
  97. func main() {
  98. l := NewLibrary()
  99. l.DoSomething(5)
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement