Skip to content

Commit 960fa9b

Browse files
aclementsgopherbot
authored andcommitted
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>
1 parent a62c290 commit 960fa9b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/sync/example_test.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package sync_test
66

77
import (
88
"fmt"
9+
"os"
910
"sync"
1011
)
1112

@@ -57,3 +58,56 @@ func ExampleOnce() {
5758
// Output:
5859
// Only once
5960
}
61+
62+
// This example uses OnceValue to perform an "expensive" computation just once,
63+
// even when used concurrently.
64+
func ExampleOnceValue() {
65+
once := sync.OnceValue(func() int {
66+
sum := 0
67+
for i := 0; i < 1000; i++ {
68+
sum += i
69+
}
70+
fmt.Println("Computed once:", sum)
71+
return sum
72+
})
73+
done := make(chan bool)
74+
for i := 0; i < 10; i++ {
75+
go func() {
76+
const want = 499500
77+
got := once()
78+
if got != want {
79+
fmt.Println("want", want, "got", got)
80+
}
81+
done <- true
82+
}()
83+
}
84+
for i := 0; i < 10; i++ {
85+
<-done
86+
}
87+
// Output:
88+
// Computed once: 499500
89+
}
90+
91+
// This example uses OnceValues to read a file just once.
92+
func ExampleOnceValues() {
93+
once := sync.OnceValues(func() ([]byte, error) {
94+
fmt.Println("Reading file once")
95+
return os.ReadFile("example_test.go")
96+
})
97+
done := make(chan bool)
98+
for i := 0; i < 10; i++ {
99+
go func() {
100+
data, err := once()
101+
if err != nil {
102+
fmt.Println("error:", err)
103+
}
104+
_ = data // Ignore the data for this example
105+
done <- true
106+
}()
107+
}
108+
for i := 0; i < 10; i++ {
109+
<-done
110+
}
111+
// Output:
112+
// Reading file once
113+
}

0 commit comments

Comments
 (0)