Source file
src/sync/example_test.go
1
2
3
4
5 package sync_test
6
7 import (
8 "fmt"
9 "os"
10 "sync"
11 )
12
13 type httpPkg struct{}
14
15 func (httpPkg) Get(url string) {}
16
17 var http httpPkg
18
19
20
21 func ExampleWaitGroup() {
22 var wg sync.WaitGroup
23 var urls = []string{
24 "http://www.golang.org/",
25 "http://www.google.com/",
26 "http://www.example.com/",
27 }
28 for _, url := range urls {
29
30 wg.Add(1)
31
32 go func(url string) {
33
34 defer wg.Done()
35
36 http.Get(url)
37 }(url)
38 }
39
40 wg.Wait()
41 }
42
43 func ExampleOnce() {
44 var once sync.Once
45 onceBody := func() {
46 fmt.Println("Only once")
47 }
48 done := make(chan bool)
49 for i := 0; i < 10; i++ {
50 go func() {
51 once.Do(onceBody)
52 done <- true
53 }()
54 }
55 for i := 0; i < 10; i++ {
56 <-done
57 }
58
59
60 }
61
62
63
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
88
89 }
90
91
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
105 done <- true
106 }()
107 }
108 for i := 0; i < 10; i++ {
109 <-done
110 }
111
112
113 }
114
View as plain text