Documentation

Overview

    Package semaphore provides a weighted semaphore implementation.

    Example (WorkerPool)

      Example_workerPool demonstrates how to use a semaphore to limit the number of goroutines working on parallel tasks.

      This use of a semaphore mimics a typical “worker pool” pattern, but without the need to explicitly shut down idle workers when the work is done.

      Output:
      
      [0 1 7 2 5 8 16 3 19 6 14 9 9 17 17 4 12 20 20 7 7 15 15 10 23 10 111 18 18 18 106 5]
      

      Index

      Examples

      Constants

      This section is empty.

      Variables

      This section is empty.

      Functions

      This section is empty.

      Types

      type Weighted

      type Weighted struct {
      	// contains filtered or unexported fields
      }

        Weighted provides a way to bound concurrent access to a resource. The callers can request access with a given weight.

        func NewWeighted

        func NewWeighted(n int64) *Weighted

          NewWeighted creates a new weighted semaphore with the given maximum combined weight for concurrent access.

          func (*Weighted) Acquire

          func (s *Weighted) Acquire(ctx context.Context, n int64) error

            Acquire acquires the semaphore with a weight of n, blocking until resources are available or ctx is done. On success, returns nil. On failure, returns ctx.Err() and leaves the semaphore unchanged.

            If ctx is already done, Acquire may still succeed without blocking.

            func (*Weighted) Release

            func (s *Weighted) Release(n int64)

              Release releases the semaphore with a weight of n.

              func (*Weighted) TryAcquire

              func (s *Weighted) TryAcquire(n int64) bool

                TryAcquire acquires the semaphore with a weight of n without blocking. On success, returns true. On failure, returns false and leaves the semaphore unchanged.

                Source Files