future.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright (C) 2014 Space Monkey, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package utils
  15. import (
  16. "sync"
  17. )
  18. // Future is a type that is essentially the inverse of a channel. With a
  19. // channel, you have multiple senders and one receiver. With a future, you can
  20. // have multiple receivers and one sender. Additionally, a future protects
  21. // against double-sends. Since this is usually used for returning function
  22. // results, we also capture and return error values as well. Use NewFuture
  23. // to initialize.
  24. type Future struct {
  25. mutex *sync.Mutex
  26. cond *sync.Cond
  27. received bool
  28. val interface{}
  29. err error
  30. }
  31. // NewFuture returns an initialized and ready Future.
  32. func NewFuture() *Future {
  33. mutex := &sync.Mutex{}
  34. return &Future{
  35. mutex: mutex,
  36. cond: sync.NewCond(mutex),
  37. received: false,
  38. val: nil,
  39. err: nil,
  40. }
  41. }
  42. // Get blocks until the Future has a value set.
  43. func (self *Future) Get() (interface{}, error) {
  44. self.mutex.Lock()
  45. defer self.mutex.Unlock()
  46. for {
  47. if self.received {
  48. return self.val, self.err
  49. }
  50. self.cond.Wait()
  51. }
  52. }
  53. // Fired returns whether or not a value has been set. If Fired is true, Get
  54. // won't block.
  55. func (self *Future) Fired() bool {
  56. self.mutex.Lock()
  57. defer self.mutex.Unlock()
  58. return self.received
  59. }
  60. // Set provides the value to present and future Get calls. If Set has already
  61. // been called, this is a no-op.
  62. func (self *Future) Set(val interface{}, err error) {
  63. self.mutex.Lock()
  64. defer self.mutex.Unlock()
  65. if self.received {
  66. return
  67. }
  68. self.received = true
  69. self.val = val
  70. self.err = err
  71. self.cond.Broadcast()
  72. }