github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/stack/mutex.go (about)

     1  package stack
     2  
     3  import "sync"
     4  
     5  type MutexStack[T any] struct {
     6  	v  []T
     7  	mu sync.Mutex
     8  }
     9  
    10  func NewMutexStack[T any]() MutexStack[T] {
    11  	return MutexStack[T]{v: make([]T, 0, 8)}
    12  }
    13  
    14  func (s *MutexStack[T]) Push(v T) {
    15  	s.mu.Lock()
    16  	s.PushUnlocked(v)
    17  	s.mu.Unlock()
    18  }
    19  
    20  func (s *MutexStack[T]) PushUnlocked(v T) {
    21  	s.v = append(s.v, v)
    22  }
    23  
    24  func (s *MutexStack[T]) Pop() (T, bool) {
    25  	s.mu.Lock()
    26  
    27  	v, ok := s.PopUnlocked()
    28  
    29  	s.mu.Unlock()
    30  
    31  	return v, ok
    32  }
    33  
    34  func (s *MutexStack[T]) PopUnlocked() (T, bool) {
    35  	var v T
    36  
    37  	if len(s.v) == 0 {
    38  		return v, false
    39  	}
    40  
    41  	v = s.v[len(s.v)-1]
    42  	s.v = s.v[:len(s.v)-1]
    43  
    44  	return v, true
    45  }