package permitpool
import "github.com/hashicorp/go-secure-stdlib/permitpool"
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 ¶
const DefaultParallelOperations = 128
DefaultParallelOperations is the default number of parallel operations allowed by the permit pool.
Types ¶
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool is used to limit maximum outstanding requests
Code:play
Output: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))
}
Generated 5 keys
func New ¶
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 ¶
Acquire returns when a permit has been acquired, or if the context is canceled.
func (*Pool) CurrentPermits ¶
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
Source Files ¶
- Version
- v1.0.0 (latest)
- Published
- Jan 22, 2025
- Platform
- linux/amd64
- Imports
- 1 packages
- Last checked
- 1 month ago –
Tools for package owners.