github.com/yacovm/fabric@v2.0.0-alpha.0.20191128145320-c5d4087dc723+incompatible/common/semaphore/semaphore.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  // Package semaphore provides an implementation of a counting semaphore.
     8  package semaphore
     9  
    10  import "context"
    11  
    12  // Semaphore is a buffered channel based implementation of a counting
    13  // semaphore.
    14  type Semaphore chan struct{}
    15  
    16  // New creates a Semaphore with the specified number of permits.
    17  func New(permits int) Semaphore {
    18  	if permits <= 0 {
    19  		panic("permits must be greater than 0")
    20  	}
    21  	return make(chan struct{}, permits)
    22  }
    23  
    24  // Acquire acquires a permit. This call will block until a permit is available
    25  // or the provided context is completed.
    26  //
    27  // If the provided context is completed, the method will return the
    28  // cancellation error.
    29  func (s Semaphore) Acquire(ctx context.Context) error {
    30  	select {
    31  	case <-ctx.Done():
    32  		return ctx.Err()
    33  	case s <- struct{}{}:
    34  		return nil
    35  	}
    36  }
    37  
    38  // Release releases a permit.
    39  func (s Semaphore) Release() {
    40  	select {
    41  	case <-s:
    42  	default:
    43  		panic("semaphore buffer is empty")
    44  	}
    45  }