queue.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Package mhayaQueue provides an efficient implementation of a multi-producer, single-consumer lock-free queue.
  2. //
  3. // The Push function is safe to call from multiple goroutines. The pop and Empty APIs must only be
  4. // called from a single, consumer goroutine.
  5. package mhayaQueue
  6. // This implementation is based on http://www.1024cores.net/home/lock-free-algorithms/queues/non-intrusive-mpsc-node-based-queue
  7. import (
  8. "sync/atomic"
  9. "unsafe"
  10. )
  11. type node struct {
  12. next *node
  13. val interface{}
  14. }
  15. type Queue struct {
  16. head, tail *node
  17. }
  18. func NewQueue() Queue {
  19. q := Queue{}
  20. stub := &node{}
  21. q.head = stub
  22. q.tail = stub
  23. return q
  24. }
  25. // Push adds x to the back of the queue.
  26. //
  27. // Push can be safely called from multiple goroutines
  28. func (q *Queue) Push(x interface{}) {
  29. n := new(node)
  30. n.val = x
  31. // current producer acquires head node
  32. prev := (*node)(atomic.SwapPointer((*unsafe.Pointer)(unsafe.Pointer(&q.head)), unsafe.Pointer(n)))
  33. // release node to consumer
  34. atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&prev.next)), unsafe.Pointer(n))
  35. }
  36. // Pop removes the item from the front of the queue or nil if the queue is empty
  37. //
  38. // Pop must be called from a single, consumer goroutine
  39. func (q *Queue) Pop() interface{} {
  40. tail := q.tail
  41. next := (*node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&tail.next)))) // acquire
  42. if next != nil {
  43. q.tail = next
  44. v := next.val
  45. next.val = nil
  46. return v
  47. }
  48. return nil
  49. }
  50. // Empty returns true if the queue is empty
  51. //
  52. // must be called from a single, consumer goroutine
  53. func (q *Queue) Empty() bool {
  54. tail := q.tail
  55. next := (*node)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&tail.next))))
  56. return next == nil
  57. }