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 ¶
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.
Click to show internal directories.
Click to hide internal directories.