@@ -6,6 +6,7 @@ package sync_test
6
6
7
7
import (
8
8
"fmt"
9
+ "os"
9
10
"sync"
10
11
)
11
12
@@ -57,3 +58,56 @@ func ExampleOnce() {
57
58
// Output:
58
59
// Only once
59
60
}
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