pool

package
v1.202405300917.1 Latest Latest
Warning

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

Go to latest
Published: May 30, 2024 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/voedger/voedger/pkg/appparts/internal/pool"
)

func main() {
	// This example demonstrates how to use Pool.

	// Create a new pool of integers.
	p := pool.New[int]([]int{1, 2, 3})

	func() {
		fmt.Println("Simple borrow-use-release")

		// Borrow a value from pool.
		v, err := p.Borrow()
		if err != nil {
			panic(err)
		}

		// Use value.
		fmt.Println(v, "enough:", p.Len())

		// Release the value to pool.
		p.Release(v)
	}()

	func() {
		fmt.Println("Borrow values until get error, then releases all borrowed")
		all := make([]int, 0, 3)

		// Borrow all values from pool.
		for v, err := p.Borrow(); err == nil; v, err = p.Borrow() {
			fmt.Println(v, "enough:", p.Len())
			all = append(all, v)
		}

		// Release borrowed values to pool.
		for _, v := range all {
			p.Release(v)
		}
	}()

}
Output:

Simple borrow-use-release
1 enough: 2
Borrow values until get error, then releases all borrowed
2 enough: 2
3 enough: 1
1 enough: 0

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNotEnough = errors.New("not enough elements in a pool")

Functions

This section is empty.

Types

type Pool

type Pool[T any] struct {
	// contains filtered or unexported fields
}

Thread-safe pool of reusable values.

Value is borrowed from poll by calling Borrow() method. After using value, it must be returned to pool by calling Release() method.

TODO: adds tests to check that pool is thread-safe

func New

func New[T any](values []T) *Pool[T]

Creates and returns a new instance of Pool. All passed to New() values are initially placed into the pool.

func (*Pool[T]) Borrow

func (p *Pool[T]) Borrow() (value T, err error)

Borrows a value from pool.

If pool is empty, returns ErrNotEnough.

Borrowed value must be returned to pool by calling Release() method.

func (*Pool[T]) Len

func (p *Pool[T]) Len() int

Returns a number of enough values in pool.

func (*Pool[T]) Release

func (p *Pool[T]) Release(value T)

Returns a value into pool.

Jump to

Keyboard shortcuts

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