ring.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. /*
  2. Copyright 2014 Workiva, LLC
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package queue
  14. import (
  15. "runtime"
  16. "sync/atomic"
  17. "time"
  18. )
  19. // roundUp takes a uint64 greater than 0 and rounds it up to the next
  20. // power of 2.
  21. func roundUp(v uint64) uint64 {
  22. v--
  23. v |= v >> 1
  24. v |= v >> 2
  25. v |= v >> 4
  26. v |= v >> 8
  27. v |= v >> 16
  28. v |= v >> 32
  29. v++
  30. return v
  31. }
  32. type node struct {
  33. position uint64
  34. data interface{}
  35. }
  36. type nodes []*node
  37. // RingBuffer is a MPMC buffer that achieves threadsafety with CAS operations
  38. // only. A put on full or get on empty call will block until an item
  39. // is put or retrieved. Calling Dispose on the RingBuffer will unblock
  40. // any blocked threads with an error. This buffer is similar to the buffer
  41. // described here: http://www.1024cores.net/home/lock-free-algorithms/queues/bounded-mpmc-queue
  42. // with some minor additions.
  43. type RingBuffer struct {
  44. _padding0 [8]uint64
  45. queue uint64
  46. _padding1 [8]uint64
  47. dequeue uint64
  48. _padding2 [8]uint64
  49. mask, disposed uint64
  50. _padding3 [8]uint64
  51. nodes nodes
  52. }
  53. func (rb *RingBuffer) init(size uint64) {
  54. size = roundUp(size)
  55. rb.nodes = make(nodes, size)
  56. for i := uint64(0); i < size; i++ {
  57. rb.nodes[i] = &node{position: i}
  58. }
  59. rb.mask = size - 1 // so we don't have to do this with every put/get operation
  60. }
  61. // Put adds the provided item to the queue. If the queue is full, this
  62. // call will block until an item is added to the queue or Dispose is called
  63. // on the queue. An error will be returned if the queue is disposed.
  64. func (rb *RingBuffer) Put(item interface{}) error {
  65. _, err := rb.put(item, false)
  66. return err
  67. }
  68. // Offer adds the provided item to the queue if there is space. If the queue
  69. // is full, this call will return false. An error will be returned if the
  70. // queue is disposed.
  71. func (rb *RingBuffer) Offer(item interface{}) (bool, error) {
  72. return rb.put(item, true)
  73. }
  74. func (rb *RingBuffer) put(item interface{}, offer bool) (bool, error) {
  75. var n *node
  76. pos := atomic.LoadUint64(&rb.queue)
  77. L:
  78. for {
  79. if atomic.LoadUint64(&rb.disposed) == 1 {
  80. return false, ErrDisposed
  81. }
  82. n = rb.nodes[pos&rb.mask]
  83. seq := atomic.LoadUint64(&n.position)
  84. switch dif := seq - pos; {
  85. case dif == 0:
  86. if atomic.CompareAndSwapUint64(&rb.queue, pos, pos+1) {
  87. break L
  88. }
  89. // case dif < 0:
  90. // panic(`Ring buffer in a compromised state during a put operation.`)
  91. default:
  92. pos = atomic.LoadUint64(&rb.queue)
  93. }
  94. if offer {
  95. return false, nil
  96. }
  97. runtime.Gosched() // free up the cpu before the next iteration
  98. }
  99. n.data = item
  100. atomic.StoreUint64(&n.position, pos+1)
  101. return true, nil
  102. }
  103. // Get will return the next item in the queue. This call will block
  104. // if the queue is empty. This call will unblock when an item is added
  105. // to the queue or Dispose is called on the queue. An error will be returned
  106. // if the queue is disposed.
  107. func (rb *RingBuffer) Get() (interface{}, error) {
  108. return rb.Poll(0)
  109. }
  110. // Poll will return the next item in the queue. This call will block
  111. // if the queue is empty. This call will unblock when an item is added
  112. // to the queue, Dispose is called on the queue, or the timeout is reached. An
  113. // error will be returned if the queue is disposed or a timeout occurs. A
  114. // non-positive timeout will block indefinitely.
  115. func (rb *RingBuffer) Poll(timeout time.Duration) (interface{}, error) {
  116. var (
  117. n *node
  118. pos = atomic.LoadUint64(&rb.dequeue)
  119. start time.Time
  120. )
  121. if timeout > 0 {
  122. start = time.Now()
  123. }
  124. L:
  125. for {
  126. if atomic.LoadUint64(&rb.disposed) == 1 {
  127. return nil, ErrDisposed
  128. }
  129. n = rb.nodes[pos&rb.mask]
  130. seq := atomic.LoadUint64(&n.position)
  131. switch dif := seq - (pos + 1); {
  132. case dif == 0:
  133. if atomic.CompareAndSwapUint64(&rb.dequeue, pos, pos+1) {
  134. break L
  135. }
  136. // case dif < 0:
  137. // panic(`Ring buffer in compromised state during a get operation.`)
  138. default:
  139. pos = atomic.LoadUint64(&rb.dequeue)
  140. }
  141. if timeout > 0 && time.Since(start) >= timeout {
  142. return nil, ErrTimeout
  143. }
  144. runtime.Gosched() // free up the cpu before the next iteration
  145. }
  146. data := n.data
  147. n.data = nil
  148. atomic.StoreUint64(&n.position, pos+rb.mask+1)
  149. return data, nil
  150. }
  151. // Len returns the number of items in the queue.
  152. func (rb *RingBuffer) Len() uint64 {
  153. return atomic.LoadUint64(&rb.queue) - atomic.LoadUint64(&rb.dequeue)
  154. }
  155. // Cap returns the capacity of this ring buffer.
  156. func (rb *RingBuffer) Cap() uint64 {
  157. return uint64(len(rb.nodes))
  158. }
  159. // Dispose will dispose of this queue and free any blocked threads
  160. // in the Put and/or Get methods. Calling those methods on a disposed
  161. // queue will return an error.
  162. func (rb *RingBuffer) Dispose() {
  163. atomic.CompareAndSwapUint64(&rb.disposed, 0, 1)
  164. }
  165. // IsDisposed will return a bool indicating if this queue has been
  166. // disposed.
  167. func (rb *RingBuffer) IsDisposed() bool {
  168. return atomic.LoadUint64(&rb.disposed) == 1
  169. }
  170. // NewRingBuffer will allocate, initialize, and return a ring buffer
  171. // with the specified size.
  172. func NewRingBuffer(size uint64) *RingBuffer {
  173. rb := &RingBuffer{}
  174. rb.init(size)
  175. return rb
  176. }