queue.go 718 B

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