Skip to content

Commit 4966af6

Browse files
seankhliaogopherbot
authored andcommitted
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>
1 parent a6666c1 commit 4966af6

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

singleflight/singleflight_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -327,3 +327,33 @@ func TestPanicDoSharedByDoChan(t *testing.T) {
327327
t.Errorf("Test subprocess failed, but the crash isn't caused by panicking in Do")
328328
}
329329
}
330+
331+
func ExampleGroup() {
332+
g := new(Group)
333+
334+
block := make(chan struct{})
335+
res1c := g.DoChan("key", func() (interface{}, error) {
336+
<-block
337+
return "func 1", nil
338+
})
339+
res2c := g.DoChan("key", func() (interface{}, error) {
340+
<-block
341+
return "func 2", nil
342+
})
343+
close(block)
344+
345+
res1 := <-res1c
346+
res2 := <-res2c
347+
348+
// Results are shared by functions executed with duplicate keys.
349+
fmt.Println("Shared:", res2.Shared)
350+
// Only the first function is executed: it is registered and started with "key",
351+
// and doesn't complete before the second funtion is registered with a duplicate key.
352+
fmt.Println("Equal results:", res1.Val.(string) == res2.Val.(string))
353+
fmt.Println("Result:", res1.Val)
354+
355+
// Output:
356+
// Shared: true
357+
// Equal results: true
358+
// Result: func 1
359+
}

0 commit comments

Comments
 (0)