github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/internal/sync/sync.go (about)

     1  package sync
     2  
     3  type Semaphore struct {
     4  	ch chan struct{}
     5  }
     6  
     7  func NewSemaphore(size int) Semaphore {
     8  	return Semaphore{
     9  		ch: make(chan struct{}, size),
    10  	}
    11  }
    12  
    13  func (sem Semaphore) Acquire() {
    14  	sem.ch <- struct{}{}
    15  }
    16  
    17  func (sem Semaphore) AcquireMaybe() bool {
    18  	select {
    19  	case sem.ch <- struct{}{}:
    20  		return true
    21  	default:
    22  		return false
    23  	}
    24  }
    25  
    26  func (sem Semaphore) Release() {
    27  	<-sem.ch
    28  }
    29  
    30  func (sem Semaphore) Len() int {
    31  	return len(sem.ch)
    32  }
    33  
    34  func (sem Semaphore) Cap() int {
    35  	return cap(sem.ch)
    36  }