diff options
author | hcpp <hcpp@ydb.tech> | 2023-11-08 12:09:41 +0300 |
---|---|---|
committer | hcpp <hcpp@ydb.tech> | 2023-11-08 12:56:14 +0300 |
commit | a361f5b98b98b44ea510d274f6769164640dd5e1 (patch) | |
tree | c47c80962c6e2e7b06798238752fd3da0191a3f6 /library/go/x/xsync/singleinflight.go | |
parent | 9478806fde1f4d40bd5a45e7cbe77237dab613e9 (diff) | |
download | ydb-a361f5b98b98b44ea510d274f6769164640dd5e1.tar.gz |
metrics have been added
Diffstat (limited to 'library/go/x/xsync/singleinflight.go')
-rw-r--r-- | library/go/x/xsync/singleinflight.go | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/library/go/x/xsync/singleinflight.go b/library/go/x/xsync/singleinflight.go new file mode 100644 index 0000000000..3beee1ea67 --- /dev/null +++ b/library/go/x/xsync/singleinflight.go @@ -0,0 +1,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)) +} |