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