You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
691 B

5 years ago
  1. package util
  2. import "sync"
  3. type node struct {
  4. data interface{}
  5. next *node
  6. }
  7. type Queue struct {
  8. head *node
  9. tail *node
  10. count int
  11. sync.RWMutex
  12. }
  13. func NewQueue() *Queue {
  14. q := &Queue{}
  15. return q
  16. }
  17. func (q *Queue) Len() int {
  18. q.RLock()
  19. defer q.RUnlock()
  20. return q.count
  21. }
  22. func (q *Queue) Enqueue(item interface{}) {
  23. q.Lock()
  24. defer q.Unlock()
  25. n := &node{data: item}
  26. if q.tail == nil {
  27. q.tail = n
  28. q.head = n
  29. } else {
  30. q.tail.next = n
  31. q.tail = n
  32. }
  33. q.count++
  34. }
  35. func (q *Queue) Dequeue() interface{} {
  36. q.Lock()
  37. defer q.Unlock()
  38. if q.head == nil {
  39. return nil
  40. }
  41. n := q.head
  42. q.head = n.next
  43. if q.head == nil {
  44. q.tail = nil
  45. }
  46. q.count--
  47. return n.data
  48. }