-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
54 lines (42 loc) · 1.3 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright (c) 2023 Bruno Marques Venceslau de Souza. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"github.com/brunomvsouza/singleflight"
)
func main() {
var group singleflight.Group[string, string]
semaphore := make(chan struct{})
res1c := group.DoChan("key", func() (string, error) {
fmt.Printf("func 1 begin\n")
defer fmt.Printf("func 1 end\n")
<-semaphore
return "func 1", nil
})
res2c := group.DoChan("key", func() (string, error) {
fmt.Printf("func 2 begin\n")
defer fmt.Printf("func 2 end\n")
<-semaphore
return "func 2", nil
})
close(semaphore)
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 == res2.Val)
fmt.Println("Result:", res1.Val)
// Output:
// Shared: true
// Equal results: true
// Result: func 1
}