semaphore

package
v2.0.0-...-e272d2b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2022 License: MIT Imports: 0 Imported by: 0

Documentation

Overview

package semaphore is like a sync.WaitGroup with an upper limit. It's useful for limiting concurrent operations.

Example Usage

// startMultiplying is a pipeline step that concurrently multiplies input numbers by a factor
func startMultiplying(concurrency, factor int, in <-chan int) <-chan int {
	out := make(chan int)
	go func() {
 		sem := semaphore.New(concurrency)
 		for i := range in {
 			// Multiply up to 'concurrency' inputs at once
 			sem.Add(1)
 			go func() {
 				out <- factor * i
 				sem.Done()
 			}()
 		}
 		// Wait for all multiplications to finish before closing the output chan
 		sem.Wait()
 		close(out)
	}()
	return out
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Semaphore

type Semaphore chan struct{}

Semaphore is like a sync.WaitGroup, except it has a maximum number of items that can be added. If that maximum is reached, Add will block until Done is called.

func New

func New(max int) Semaphore

New returns a new Semaphore

func (Semaphore) Add

func (s Semaphore) Add(delta int)

Add adds delta, which may be negative, to the semaphore buffer. If the buffer becomes 0, all goroutines blocked by Wait are released. If the buffer goes negative, Add will block until another goroutine makes it positive. If the buffer exceeds max, Add will block until another goroutine decrements the buffer.

func (Semaphore) Done

func (s Semaphore) Done()

Done decrements the semaphore by 1

func (Semaphore) Wait

func (s Semaphore) Wait()

Wait blocks until the semaphore is buffer is empty

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL