-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathgate.go
89 lines (79 loc) · 2.03 KB
/
gate.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
87
88
89
// Copyright 2023 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 quic
import "context"
// An gate is a monitor (mutex + condition variable) with one bit of state.
//
// The condition may be either set or unset.
// Lock operations may be unconditional, or wait for the condition to be set.
// Unlock operations record the new state of the condition.
type gate struct {
// When unlocked, exactly one of set or unset contains a value.
// When locked, neither chan contains a value.
set chan struct{}
unset chan struct{}
}
// newGate returns a new, unlocked gate with the condition unset.
func newGate() gate {
g := newLockedGate()
g.unlock(false)
return g
}
// newLockedGate returns a new, locked gate.
func newLockedGate() gate {
return gate{
set: make(chan struct{}, 1),
unset: make(chan struct{}, 1),
}
}
// lock acquires the gate unconditionally.
// It reports whether the condition is set.
func (g *gate) lock() (set bool) {
select {
case <-g.set:
return true
case <-g.unset:
return false
}
}
// waitAndLock waits until the condition is set before acquiring the gate.
// If the context expires, waitAndLock returns an error and does not acquire the gate.
func (g *gate) waitAndLock(ctx context.Context, testHooks connTestHooks) error {
if testHooks != nil {
return testHooks.waitUntil(ctx, g.lockIfSet)
}
select {
case <-g.set:
return nil
default:
}
select {
case <-g.set:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// lockIfSet acquires the gate if and only if the condition is set.
func (g *gate) lockIfSet() (acquired bool) {
select {
case <-g.set:
return true
default:
return false
}
}
// unlock sets the condition and releases the gate.
func (g *gate) unlock(set bool) {
if set {
g.set <- struct{}{}
} else {
g.unset <- struct{}{}
}
}
// unlockFunc sets the condition to the result of f and releases the gate.
// Useful in defers.
func (g *gate) unlockFunc(f func() bool) {
g.unlock(f())
}