aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/x/xsync/singleinflight.go
blob: 3beee1ea67280a3e1c428e91d8ed8e8d4f4d098d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package xsync

import (
	"sync"
	"sync/atomic"
)

// SingleInflight allows only one execution of function at time.
// For more exhaustive functionality see https://pkg.go.dev/golang.org/x/sync/singleflight.
type SingleInflight struct {
	updatingOnce atomic.Value
}

// NewSingleInflight creates new SingleInflight.
func NewSingleInflight() SingleInflight {
	var v atomic.Value
	v.Store(new(sync.Once))
	return SingleInflight{updatingOnce: v}
}

// Do executes the given function, making sure that only one execution is in-flight.
// If another caller comes in, it waits for the original to complete.
func (i *SingleInflight) Do(f func()) {
	i.getOnce().Do(func() {
		f()
		i.setOnce()
	})
}

func (i *SingleInflight) getOnce() *sync.Once {
	return i.updatingOnce.Load().(*sync.Once)
}

func (i *SingleInflight) setOnce() {
	i.updatingOnce.Store(new(sync.Once))
}