singleflight

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT 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[T any] struct {
	// contains filtered or unexported fields
}

Group represents a class of work and forms a namespace in which units of work can be executed with duplicate suppression. Unlike the original singleflight Group, this version uses generics. A Group[T]’s Do method returns a Result[T], so the value has the same type T used to create the Group.

Example
g := NewGroup[int]()

block := make(chan struct{})
started := make(chan struct{}, 2)

var r1, r2 Result[int]
var wg sync.WaitGroup

wg.Add(2)
go func() {
	defer wg.Done()
	started <- struct{}{}
	r1 = g.Do("key", func() (int, error) {
		<-block
		return 1, nil
	})
}()

go func() {
	defer wg.Done()
	started <- struct{}{}
	r2 = g.Do("key", func() (int, error) {
		<-block
		return 2, nil
	})
}()

<-started
<-started

close(block)
wg.Wait()

fmt.Println("Equal result:", r1.Val == r2.Val)
Output:

Equal result: true

func NewGroup

func NewGroup[T any]() *Group[T]

func (*Group[T]) Do

func (g *Group[T]) Do(key string, fn func() (T, error)) Result[T]

Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results.

func (*Group[T]) Stats

func (g *Group[T]) Stats() *Stats

type Result

type Result[T any] struct {
	Err error

	Shared  bool
	Initial bool

	Val T
}

Result is the return value of a singleflight.Do call.

The shared field indicates whether the value was given to multiple callers. The initial field indicates whether this is the first call to Do for the given key.

type Stats

type Stats struct {
	NumCalls           atomic.Int64
	NumSuppressedCalls atomic.Int64
}

Stats contains statistics about the singleflight.Group. NumCalls is the number of calls to Do. NumSuppressedCalls is the number of calls to Do that were suppressed due to a previous call and are waiting for the results.

Jump to

Keyboard shortcuts

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