https://github.com/jimmicro/singleflight
go-zero/core/syncx/singleflight.go but with Go 1.18 generics
https://github.com/jimmicro/singleflight
generic go singleflight
Last synced: 6 months ago
JSON representation
go-zero/core/syncx/singleflight.go but with Go 1.18 generics
- Host: GitHub
- URL: https://github.com/jimmicro/singleflight
- Owner: jimmicro
- Created: 2022-04-26T14:35:08.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2025-03-14T06:32:58.000Z (over 1 year ago)
- Last Synced: 2025-08-09T21:38:36.583Z (11 months ago)
- Topics: generic, go, singleflight
- Language: Go
- Homepage:
- Size: 6.84 KB
- Stars: 4
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# singleflight
This repo is a hard fork of [go-zero/singleflight.go at master · zeromicro/go-zero (github.com)](https://github.com/zeromicro/go-zero/blob/master/core/syncx/singleflight.go) that adds generics to the Group type so that there is no need for type assertion when using the library.
## Install
```shell
go get github.com/jimmicro/singleflight@latest
```
## Usage
```go
package main
import (
"log"
"sync"
"sync/atomic"
"time"
"github.com/jimmicro/singleflight"
)
func main() {
g := singleflight.New[string]()
c := make(chan string)
var calls int32
// 给 calls 加 1
fn := func() (string, error) {
atomic.AddInt32(&calls, 1)
return <-c, nil
}
const n = 10
var wg sync.WaitGroup
// 同时加 1 最终的结果只能是 1
for i := 0; i < n; i++ {
wg.Add(1)
go func() {
v, err := g.Do("key", fn)
if err != nil {
log.Fatalf("Do error: %v", err)
}
if v != "bar" {
log.Fatalf("got %q; want %q", v, "bar")
}
wg.Done()
}()
}
time.Sleep(100 * time.Millisecond) // let goroutines above block
c <- "bar"
wg.Wait()
if got := atomic.LoadInt32(&calls); got != 1 {
log.Fatalf("number of calls = %d; want 1", got)
}
log.Printf("done %v", calls)
}
```