-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcustom_sync_waitgroup.go
More file actions
76 lines (62 loc) · 1.19 KB
/
Copy pathcustom_sync_waitgroup.go
File metadata and controls
76 lines (62 loc) · 1.19 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
/*
## Custome Sync.WaitGroup
Write our own version of `Sync.WaitGroup` which basically mimics the overall
behaviour of the native liberary.
**Time Required: 15 mins max**
### Thinks look for
- Not doing long polling, use channels and mutex
- What if not `add` is called
- What if not `wait` is called
- And thinking for other corner cases
*/
import (
"fmt"
"sync"
"time"
)
type WaitGroup struct {
counter int
done chan bool
wait bool
mu sync.Mutex
}
func main() {
wg := newWaitGroup()
count := 10
wg.Add(count)
for i := 0; i < count; i++ {
go func(i int) {
time.Sleep(100 * time.Millisecond)
fmt.Printf("%d\t done\n", i+1)
wg.Done()
}(i)
}
wg.Wait()
}
func newWaitGroup() *WaitGroup {
return &WaitGroup{
counter: 0,
done: make(chan bool),
}
}
func (cwg *WaitGroup) Add(x int) {
cwg.mu.Lock()
defer cwg.mu.Unlock()
cwg.counter += x
// send signal on all goroutines complete and if wait is started
if cwg.counter == 0 && cwg.wait {
cwg.done <- true
}
}
func (cwg *WaitGroup) Done() {
cwg.Add(-1)
}
func (cwg *WaitGroup) Wait() {
cwg.wait = true
if cwg.counter == 0 {
// all goroutines might completed before wait
return
}
<-cwg.done
}