File size: 1,424 Bytes
1e92f2d |
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
import "sync"
// depTree manages tasks with dependencies, allowing them to execute in parallel
// as quickly as possible.
type depTree struct {
done map[string]bool
mx sync.Mutex
ch chan struct{}
}
// newDepTree creates a new depTree that can be used to managed parallel tasks.
func newDepTree() *depTree {
return &depTree{
done: make(map[string]bool),
ch: make(chan struct{}),
}
}
// Start registers a new task ID and switches it to a "busy" state.
func (dt *depTree) Start(id string) {
dt.mx.Lock()
defer dt.mx.Unlock()
dt.done[id] = false
}
// Done switches the provided task ID to a "done" state. It is registered if not already.
func (dt *depTree) Done(id string) {
dt.mx.Lock()
defer dt.mx.Unlock()
dt.done[id] = true
close(dt.ch)
dt.ch = make(chan struct{})
}
// WaitFor will block until all provided ids are registered, and reported as "done".
func (dt *depTree) WaitFor(ids ...string) {
for {
isDone := true
dt.mx.Lock()
for _, id := range ids {
if !dt.done[id] {
isDone = false
break
}
}
ch := dt.ch
dt.mx.Unlock()
if isDone {
return
}
<-ch
}
}
// Wait will block until all registered IDs are reported as "done".
func (dt *depTree) Wait() {
for {
isDone := true
dt.mx.Lock()
for _, val := range dt.done {
if !val {
isDone = false
break
}
}
ch := dt.ch
dt.mx.Unlock()
if isDone {
return
}
<-ch
}
}
|