By Golang

  1. // Package queue creates a ItemQueue data structure for the Item type
  2. package queue
  3. import (
  4. "sync"
  5. )
  6. // Item the type of the queue
  7. type Item interface{}
  8. // ItemQueue the queue of Items
  9. type ItemQueue struct {
  10. items []Item
  11. lock sync.RWMutex
  12. }
  13. // New creates a new ItemQueue
  14. func (s *ItemQueue) New() *ItemQueue {
  15. s.lock.Lock()
  16. s.items = []Item{}
  17. s.lock.Unlock()
  18. return s
  19. }
  20. // Enqueue adds an Item to the end of the queue
  21. func (s *ItemQueue) Enqueue(t Item) {
  22. s.lock.Lock()
  23. s.items = append(s.items, t)
  24. s.lock.Unlock()
  25. }
  26. // Dequeue removes an Item from the start of the queue
  27. func (s *ItemQueue) Dequeue() *Item {
  28. s.lock.Lock()
  29. item := s.items[0]
  30. s.items = s.items[1:len(s.items)]
  31. s.lock.Unlock()
  32. return &item
  33. }
  34. // Front returns the item next in the queue, without removing it
  35. func (s *ItemQueue) Front() *Item {
  36. s.lock.RLock()
  37. item := s.items[0]
  38. s.lock.RUnlock()
  39. return &item
  40. }
  41. // IsEmpty returns true if the queue is empty
  42. func (s *ItemQueue) IsEmpty() bool {
  43. s.lock.RLock()
  44. defer s.lock.RUnlock()
  45. return len(s.items) == 0
  46. }
  47. // Size returns the number of Items in the queue
  48. func (s *ItemQueue) Size() int {
  49. s.lock.RLock()
  50. defer s.lock.RUnlock()
  51. return len(s.items)
  52. }