github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/queues/lscq/lscq_safe.go (about) 1 package lscq 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/structure/queues" 5 "sync" 6 ) 7 8 var _ queues.Queue[any] = (*QueueSafe[any])(nil) 9 10 func NewSafe[E any]() *QueueSafe[E] { 11 return &QueueSafe[E]{ 12 unsafe: New[E](), 13 } 14 } 15 16 type QueueSafe[E any] struct { 17 unsafe *Queue[E] 18 lock sync.Mutex 19 } 20 21 func (s *QueueSafe[E]) Enqueue(value E) { 22 s.lock.Lock() 23 defer s.lock.Unlock() 24 s.unsafe.Enqueue(value) 25 26 } 27 28 func (s *QueueSafe[E]) Dequeue() (E, bool) { 29 s.lock.Lock() 30 defer s.lock.Unlock() 31 return s.unsafe.Dequeue() 32 } 33 34 func (s *QueueSafe[E]) Peek() (E, bool) { 35 s.lock.Lock() 36 defer s.lock.Unlock() 37 return s.unsafe.Peek() 38 } 39 40 func (s *QueueSafe[E]) Empty() bool { 41 s.lock.Lock() 42 defer s.lock.Unlock() 43 return s.unsafe.Empty() 44 } 45 46 func (s *QueueSafe[E]) Size() int { 47 s.lock.Lock() 48 defer s.lock.Unlock() 49 return s.unsafe.Size() 50 } 51 52 func (s *QueueSafe[E]) Clear() { 53 s.lock.Lock() 54 defer s.lock.Unlock() 55 s.unsafe.Clear() 56 57 } 58 59 func (s *QueueSafe[E]) Values() []E { 60 s.lock.Lock() 61 defer s.lock.Unlock() 62 return s.unsafe.Values() 63 } 64 65 func (s *QueueSafe[E]) String() string { 66 s.lock.Lock() 67 defer s.lock.Unlock() 68 return s.unsafe.String() 69 }