fifo.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package collection
  2. import "sync"
  3. type Queue struct {
  4. lock sync.Mutex
  5. elements []interface{}
  6. size int
  7. head int
  8. tail int
  9. count int
  10. }
  11. func NewQueue(size int) *Queue {
  12. return &Queue{
  13. elements: make([]interface{}, size),
  14. size: size,
  15. }
  16. }
  17. func (q *Queue) Empty() bool {
  18. q.lock.Lock()
  19. empty := q.count == 0
  20. q.lock.Unlock()
  21. return empty
  22. }
  23. func (q *Queue) Put(element interface{}) {
  24. q.lock.Lock()
  25. defer q.lock.Unlock()
  26. if q.head == q.tail && q.count > 0 {
  27. nodes := make([]interface{}, len(q.elements)+q.size)
  28. copy(nodes, q.elements[q.head:])
  29. copy(nodes[len(q.elements)-q.head:], q.elements[:q.head])
  30. q.head = 0
  31. q.tail = len(q.elements)
  32. q.elements = nodes
  33. }
  34. q.elements[q.tail] = element
  35. q.tail = (q.tail + 1) % len(q.elements)
  36. q.count++
  37. }
  38. func (q *Queue) Take() (interface{}, bool) {
  39. q.lock.Lock()
  40. defer q.lock.Unlock()
  41. if q.count == 0 {
  42. return nil, false
  43. }
  44. element := q.elements[q.head]
  45. q.head = (q.head + 1) % len(q.elements)
  46. q.count--
  47. return element, true
  48. }