singleflight

package
v1.7.11 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2024 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package singleflight provides a duplicate function call suppression mechanism.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

type Group[V any] interface {
	Do(ctx context.Context, key string, fn func(context.Context) (V, error)) (v V, shared bool, err error)
	DoChan(ctx context.Context, key string, fn func(context.Context) (V, error)) <-chan Result[V]
	Forget(key string)
}

Group represents interface for zero time cache.

Example
g := New[string]()

block := make(chan struct{})
res1c := g.DoChan(context.Background(), "key", func(context.Context) (string, error) {
	<-block
	return "func 1", nil
})
res2c := g.DoChan(context.Background(), "key", func(context.Context) (string, error) {
	<-block
	return "func 2", nil
})
close(block)

res1 := <-res1c
res2 := <-res2c

// Results are shared by functions executed with duplicate keys.
fmt.Println("Shared:", res2.Shared)
// Only the first function is executed: it is registered and started with "key",
// and doesn't complete before the second function is registered with a duplicate key.
fmt.Println("Equal results:", res1.Val == res2.Val)
fmt.Println("Result:", res1.Val)
Output:

Shared: true
Equal results: true
Result: func 1

func New

func New[V any]() Group[V]

New returns Group implementation.

type Result

type Result[V any] struct {
	Val    V
	Err    error
	Shared bool
}

Result holds the results of Do, so they can be passed on a channel.

Jump to

Keyboard shortcuts

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