queue.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package util
  2. import (
  3. "container/list"
  4. "sync"
  5. )
  6. // Queue concurrency safe list
  7. type Queue struct {
  8. l *list.List
  9. m sync.Mutex
  10. }
  11. // NewQueue new queue
  12. func NewQueue() *Queue {
  13. return &Queue{l: list.New()}
  14. }
  15. // PushBack inserts a new element e with value v at the back of list l and returns e.
  16. func (q *Queue) PushBack(v interface{}) *list.Element {
  17. q.m.Lock()
  18. defer q.m.Unlock()
  19. return q.l.PushBack(v)
  20. }
  21. // PushFront inserts a new element e with value v at the front of list l and returns e.
  22. func (q *Queue) PushFront(v interface{}) *list.Element {
  23. q.m.Lock()
  24. defer q.m.Unlock()
  25. return q.l.PushFront(v)
  26. }
  27. // InsertBefore inserts a new element e with value v immediately before mark and returns e.
  28. // If mark is not an element of l, the list is not modified.
  29. // The mark must not be nil.
  30. func (q *Queue) InsertBefore(v interface{}, mark *list.Element) *list.Element {
  31. q.m.Lock()
  32. defer q.m.Unlock()
  33. return q.l.InsertBefore(v, mark)
  34. }
  35. // InsertAfter inserts a new element e with value v immediately after mark and returns e.
  36. // If mark is not an element of l, the list is not modified.
  37. // The mark must not be nil.
  38. func (q *Queue) InsertAfter(v interface{}, mark *list.Element) *list.Element {
  39. q.m.Lock()
  40. defer q.m.Unlock()
  41. return q.l.InsertAfter(v, mark)
  42. }
  43. // Remove removes e from l if e is an element of list l.
  44. // It returns the element value e.Value.
  45. // The element must not be nil.
  46. func (q *Queue) Remove(e *list.Element) interface{} {
  47. q.m.Lock()
  48. defer q.m.Unlock()
  49. return q.l.Remove(e)
  50. }
  51. // Len returns the number of elements of list l.
  52. // The complexity is O(1).
  53. func (q *Queue) Len() int {
  54. q.m.Lock()
  55. defer q.m.Unlock()
  56. return q.l.Len()
  57. }
  58. // Back returns the last element of list l or nil if the list is empty.
  59. func (q *Queue) Back() *list.Element {
  60. q.m.Lock()
  61. defer q.m.Unlock()
  62. return q.l.Back()
  63. }
  64. // Front returns the first element of list l or nil if the list is empty.
  65. func (q *Queue) Front() *list.Element {
  66. q.m.Lock()
  67. defer q.m.Unlock()
  68. return q.l.Front()
  69. }
  70. // Init initializes or clears list l.
  71. func (q *Queue) Init(v interface{}, mark *list.Element) *list.List {
  72. q.m.Lock()
  73. defer q.m.Unlock()
  74. return q.l.Init()
  75. }