queue.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import "sync"
  3. type queue struct {
  4. buf []interface{}
  5. length int
  6. mux *sync.RWMutex
  7. }
  8. func newQueue() *queue {
  9. return &queue{make([]interface{}, 0), 0, &sync.RWMutex{}}
  10. }
  11. func (q *queue) rPush(e interface{}) {
  12. q.mux.Lock()
  13. defer q.mux.Unlock()
  14. q.buf = append(q.buf, e)
  15. q.length += 1
  16. }
  17. func (q *queue) rPushs(elements ...interface{}) {
  18. q.mux.Lock()
  19. defer q.mux.Unlock()
  20. q.buf = append(q.buf, elements...)
  21. q.length += len(elements)
  22. }
  23. func (q *queue) lPush(e interface{}) {
  24. q.mux.Lock()
  25. defer q.mux.Unlock()
  26. q.buf = append([]interface{}{e}, q.buf...)
  27. q.length += 1
  28. }
  29. func (q *queue) rPop() interface{} {
  30. q.mux.Lock()
  31. if q.length == 0 {
  32. return nil
  33. }
  34. n := q.buf[q.length-1]
  35. q.buf = q.buf[:q.length-1]
  36. q.length -= 1
  37. q.mux.Unlock()
  38. return n
  39. }
  40. func (q *queue) lPop() interface{} {
  41. q.mux.Lock()
  42. if q.length == 0 {
  43. return nil
  44. }
  45. n := q.buf[0]
  46. q.buf = q.buf[1:]
  47. q.length -= 1
  48. q.mux.Unlock()
  49. return n
  50. }
  51. func (q *queue) lGet() interface{} {
  52. q.mux.RLock()
  53. defer q.mux.RUnlock()
  54. if q.length == 0 {
  55. return nil
  56. }
  57. return q.buf[0]
  58. }
  59. func (q *queue) rGet() interface{} {
  60. q.mux.RLock()
  61. defer q.mux.RUnlock()
  62. if q.length == 0 {
  63. return nil
  64. }
  65. return q.buf[q.length-1]
  66. }
  67. func (q *queue) getLen() int {
  68. q.mux.RLock()
  69. defer q.mux.RUnlock()
  70. return q.length
  71. }