-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwaitgroup.go
More file actions
45 lines (41 loc) · 1.08 KB
/
waitgroup.go
File metadata and controls
45 lines (41 loc) · 1.08 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
package async
// A WaitGroup is a [Signal] with a counter.
//
// Calling the Add or Done method of a WaitGroup, in a [Task] function,
// updates the counter and, when the counter becomes zero, resumes any
// coroutine that is watching the WaitGroup.
//
// A WaitGroup must not be shared by more than one [Executor].
type WaitGroup struct {
Signal
n int
}
// Add adds delta, which may be negative, to the [WaitGroup] counter.
// If the [WaitGroup] counter becomes zero, Add resumes any coroutine that
// is watching wg.
// If the [WaitGroup] counter is negative, Add panics.
func (wg *WaitGroup) Add(delta int) {
if wg.n >= 0 {
wg.n += delta
}
if wg.n < 0 {
panic("async(WaitGroup): negative counter")
}
if wg.n == 0 && delta != 0 {
wg.Notify()
}
}
// Done decrements the [WaitGroup] counter by one.
func (wg *WaitGroup) Done() {
wg.Add(-1)
}
// Await returns a [Task] that awaits until the [WaitGroup] counter becomes
// zero, and then ends.
func (wg *WaitGroup) Await() Task {
return func(co *Coroutine) Result {
if wg.n != 0 {
return co.Yield(wg)
}
return co.End()
}
}