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 <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>
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 @@
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
+}