Skip to content

Commit

Permalink
singleflight: example for using Group
Browse files Browse the repository at this point in the history
Fixes golang/go#60208

Change-Id: I422a45c0f139ba47045f47cec1c96d300a2a424f
Reviewed-on: https://go-review.googlesource.com/c/sync/+/496535
Run-TryBot: Bryan Mills <bcmills@google.com>
Auto-Submit: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
  • Loading branch information
seankhliao authored and gopherbot committed May 23, 2023
1 parent a6666c1 commit 4966af6
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions singleflight/singleflight_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -327,3 +327,33 @@ func TestPanicDoSharedByDoChan(t *testing.T) {
t.Errorf("Test subprocess failed, but the crash isn't caused by panicking in Do")
}
}

func ExampleGroup() {
g := new(Group)

block := make(chan struct{})
res1c := g.DoChan("key", func() (interface{}, error) {
<-block
return "func 1", nil
})
res2c := g.DoChan("key", func() (interface{}, error) {
<-block
return "func 2", nil
})
close(block)

res1 := <-res1c
res2 := <-res2c

// Results are shared by functions executed with duplicate keys.
fmt.Println("Shared:", res2.Shared)
// Only the first function is executed: it is registered and started with "key",
// and doesn't complete before the second funtion is registered with a duplicate key.
fmt.Println("Equal results:", res1.Val.(string) == res2.Val.(string))
fmt.Println("Result:", res1.Val)

// Output:
// Shared: true
// Equal results: true
// Result: func 1
}

0 comments on commit 4966af6

Please sign in to comment.