-
Notifications
You must be signed in to change notification settings - Fork 394
/
workgroup.go
86 lines (71 loc) · 1.42 KB
/
workgroup.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information
package sync2
import (
"sync"
)
// WorkGroup implements waitable and closable group of workers
type WorkGroup struct {
mu sync.Mutex
cond sync.Cond
initialized bool
closed bool
workers int
}
// init initializes work group
func (group *WorkGroup) init() {
if !group.initialized {
group.cond.L = &group.mu
}
}
// Go starts func and tracks the execution.
// Returns false when WorkGroup has been closed.
func (group *WorkGroup) Go(fn func()) bool {
if !group.Start() {
return false
}
go func() {
defer group.Done()
fn()
}()
return true
}
// Start returns true when work can be started
func (group *WorkGroup) Start() bool {
group.mu.Lock()
defer group.mu.Unlock()
group.init()
if group.closed {
return false
}
group.workers++
return true
}
// Done finishes a pending work item
func (group *WorkGroup) Done() {
group.mu.Lock()
defer group.mu.Unlock()
group.workers--
if group.workers < 0 {
panic("worker count below zero")
}
if group.workers == 0 {
group.cond.Broadcast()
}
}
// Wait waits for all workers to finish.
func (group *WorkGroup) Wait() {
group.mu.Lock()
defer group.mu.Unlock()
group.init()
for group.workers != 0 {
group.cond.Wait()
}
}
// Close prevents from new work being started.
func (group *WorkGroup) Close() {
group.mu.Lock()
defer group.mu.Unlock()
group.init()
group.closed = true
}