permitpool

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2025 License: MPL-2.0 Imports: 1 Imported by: 20

Documentation

Overview

Package permitpool exposes a synchronization primitive for limiting the number of concurrent operations. See the Pool example for a simple use case.

Index

Examples

Constants

View Source
const DefaultParallelOperations = 128

DefaultParallelOperations is the default number of parallel operations allowed by the permit pool.

Variables

This section is empty.

Functions

This section is empty.

Types

type Pool

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

Pool is used to limit maximum outstanding requests

Example
package main

import (
	"context"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"fmt"
	"sync"

	"github.com/hashicorp/go-secure-stdlib/permitpool"
)

func main() {
	// Create a new permit pool with 2 permits.
	// This limits the number of concurrent operations to 2.
	pool := permitpool.New(2)
	ctx := context.Background()

	keys := make([]*ecdsa.PrivateKey, 5)
	wg := &sync.WaitGroup{}
	for i := range 5 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			// Acquire a permit from the pool. This
			// will block until a permit is available
			// and assigned to this goroutine.
			pool.Acquire(ctx)
			// Ensure the permit is returned to the pool upon
			// completion of the operation.
			defer pool.Release()

			// Perform some expensive operation
			key, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
			if err != nil {
				fmt.Println("Failed to generate key:", err)
				return
			}
			keys[i] = key
		}()
	}
	wg.Wait()
	fmt.Printf("Generated %d keys\n", len(keys))
}
Output:

Generated 5 keys

func New

func New(permits int) *Pool

New returns a new permit pool with the provided number of permits. If permits is less than 1, the default number of parallel operations is used.

func (*Pool) Acquire

func (c *Pool) Acquire(ctx context.Context) error

Acquire returns when a permit has been acquired, or if the context is canceled.

func (*Pool) CurrentPermits

func (c *Pool) CurrentPermits() int

CurrentPermits gets the number of used permits. This corresponds to the number of running operations.

func (*Pool) Release

func (c *Pool) Release()

Release returns a permit to the pool

Jump to

Keyboard shortcuts

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