-
Notifications
You must be signed in to change notification settings - Fork 0
/
starter.go
69 lines (56 loc) · 1.13 KB
/
starter.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
package starter
import (
"sync"
"time"
)
type Pistol struct {
m *sync.Mutex
r *sync.Cond
s *sync.Cond
waiting int
}
// Ready creates a new starter pistol to sync the start time of multiple runners.
func Ready() *Pistol {
m := &sync.Mutex{}
r := sync.NewCond(m)
s := sync.NewCond(m)
return &Pistol{
m: m,
r: r,
s: s,
waiting: 0,
}
}
// Steady makes sure the expected number of runners are waiting for the Go.
func (p *Pistol) Steady(expect int) *Pistol {
if expect <= 0 {
// no-op
return p
}
p.m.Lock()
// fast path, the number is already satisfied
if p.waiting >= expect {
p.m.Unlock()
return p
}
// wait for our condition to be fulfilled
for p.waiting < expect {
p.s.Wait()
}
p.m.Unlock()
return p
}
// Go signals the runners to start and returns the current time for easy measurements.
func (p *Pistol) Go() time.Time {
p.r.Broadcast()
return time.Now()
}
// Wait blocks the runners until Go has been called.
func (p *Pistol) Wait() {
p.m.Lock()
p.waiting++
p.s.Broadcast() // notify any Steadys that may be waiting
p.r.Wait()
p.waiting--
p.m.Unlock()
}