@@ -38,43 +38,43 @@ Here's a simple example of how to protect a function from concurrent calls.
3838package main
3939
4040import (
41- " context"
42- " fmt"
43- " sync"
44- " time"
41+ " context"
42+ " fmt"
43+ " sync"
44+ " time"
4545
46- " resenje.org/singleflight"
46+ " resenje.org/singleflight"
4747)
4848
4949func main () {
50- var g singleflight.Group [string , string ]
51- var wg sync.WaitGroup
52- n := 5
53-
54- // Make 5 concurrent calls for the same key.
55- wg.Add (n)
56- for i := 0 ; i < n; i++ {
57- go func (i int ) {
58- defer wg.Done ()
59-
60- // The function will only be executed for the first call.
61- // All other calls will wait and receive the same result.
62- v , shared , err := g.Do (context.Background (), " user-profile" , func (ctx context.Context ) (string , error ) {
63- fmt.Println (" Fetching user profile from database..." )
64- time.Sleep (100 * time.Millisecond ) // Simulate slow DB query
65- return " User data for John Doe" , nil
66- })
67-
68- if err != nil {
69- fmt.Printf (" Goroutine %d : encountered an error: %v \n " , i, err)
70- return
71- }
72-
73- fmt.Printf (" Goroutine %d : got result '%s ' (shared: %t )\n " , i, v, shared)
74- }(i )
75- }
76-
77- wg.Wait ()
50+ var g singleflight.Group [string , string ]
51+ var wg sync.WaitGroup
52+ n := 5
53+
54+ // Make 5 concurrent calls for the same key.
55+ wg.Add (n)
56+ for i := range n {
57+ wg. Go ( func () {
58+ defer wg.Done ()
59+
60+ // The function will only be executed for the first call.
61+ // All other calls will wait and receive the same result.
62+ v , shared , err := g.Do (context.Background (), " user-profile" , func (ctx context.Context ) (string , error ) {
63+ fmt.Println (" Fetching user profile from database..." )
64+ time.Sleep (100 * time.Millisecond ) // Simulate slow DB query
65+ return " User data for John Doe" , nil
66+ })
67+
68+ if err != nil {
69+ fmt.Printf (" Goroutine %d : encountered an error: %v \n " , i, err)
70+ return
71+ }
72+
73+ fmt.Printf (" Goroutine %d : got result '%s ' (shared: %t )\n " , i, v, shared)
74+ } )
75+ }
76+
77+ wg.Wait ()
7878}
7979```
8080
0 commit comments