Skip to content

Instantly share code, notes, and snippets.

@yumed15
Created November 23, 2023 17:16
Show Gist options
  • Save yumed15/9716396c68a05252afa1c35496110965 to your computer and use it in GitHub Desktop.
Save yumed15/9716396c68a05252afa1c35496110965 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
"golang.org/x/sync/singleflight"
)
var sf singleflight.Group
func fetchData(key string) (interface{}, error) {
// Simulating fetching data, e.g., from a database or external API
time.Sleep(2 * time.Second)
return fmt.Sprintf("Data for key: %s", key), nil
}
func SingleFlightDemo() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
// Use the Do method to ensure that the data is fetched only once
val, err, _ := sf.Do(fmt.Sprintf("key%d", id), func() (interface{}, error) {
return fetchData(fmt.Sprintf("key%d", id))
})
if err != nil {
fmt.Printf("Error fetching data: %v\n", err)
return
}
fmt.Printf("Goroutine %d got data: %v\n", id, val)
}(i)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment