From 4966af63bb0cd2fe6d8cf9198904d30401b05fbd Mon Sep 17 00:00:00 2001 From: Sean Liao Date: Fri, 19 May 2023 20:29:37 +0100 Subject: [PATCH] singleflight: example for using Group Fixes golang/go#60208 Change-Id: I422a45c0f139ba47045f47cec1c96d300a2a424f Reviewed-on: https://go-review.googlesource.com/c/sync/+/496535 Run-TryBot: Bryan Mills Auto-Submit: Bryan Mills TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: Bryan Mills --- singleflight/singleflight_test.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/singleflight/singleflight_test.go b/singleflight/singleflight_test.go index 4a4e0b8..bb25a1e 100644 --- a/singleflight/singleflight_test.go +++ b/singleflight/singleflight_test.go @@ -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 +}