mirror of https://github.com/golang/go.git
sync: add examples for OnceValue and OnceValues
Updates #56102. Change-Id: I2ee2dbc43b4333511d9d23752fdc574dfbf5f5bd Reviewed-on: https://go-review.googlesource.com/c/go/+/481062 Reviewed-by: Andrew Gerrand <adg@golang.org> Auto-Submit: Austin Clements <austin@google.com> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Joedian Reid <joedian@google.com>
This commit is contained in:
parent
a62c290c50
commit
960fa9bf66
|
|
@ -6,6 +6,7 @@ package sync_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
"sync"
|
"sync"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -57,3 +58,56 @@ func ExampleOnce() {
|
||||||
// Output:
|
// Output:
|
||||||
// Only once
|
// Only once
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// This example uses OnceValue to perform an "expensive" computation just once,
|
||||||
|
// even when used concurrently.
|
||||||
|
func ExampleOnceValue() {
|
||||||
|
once := sync.OnceValue(func() int {
|
||||||
|
sum := 0
|
||||||
|
for i := 0; i < 1000; i++ {
|
||||||
|
sum += i
|
||||||
|
}
|
||||||
|
fmt.Println("Computed once:", sum)
|
||||||
|
return sum
|
||||||
|
})
|
||||||
|
done := make(chan bool)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
go func() {
|
||||||
|
const want = 499500
|
||||||
|
got := once()
|
||||||
|
if got != want {
|
||||||
|
fmt.Println("want", want, "got", got)
|
||||||
|
}
|
||||||
|
done <- true
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
// Computed once: 499500
|
||||||
|
}
|
||||||
|
|
||||||
|
// This example uses OnceValues to read a file just once.
|
||||||
|
func ExampleOnceValues() {
|
||||||
|
once := sync.OnceValues(func() ([]byte, error) {
|
||||||
|
fmt.Println("Reading file once")
|
||||||
|
return os.ReadFile("example_test.go")
|
||||||
|
})
|
||||||
|
done := make(chan bool)
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
go func() {
|
||||||
|
data, err := once()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println("error:", err)
|
||||||
|
}
|
||||||
|
_ = data // Ignore the data for this example
|
||||||
|
done <- true
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
// Reading file once
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue