blob: 5b4f8a8ee417625db78b6d83ceefa8a8e098c912 (
plain)
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
|
package main
import (
"fmt"
"sort"
"sync"
"time"
)
// JobWaitGroup is like sync.WaitGroup, but keeps track of job status,
// and tracks how long each job took.
type JobWaitGroup struct {
lock sync.RWMutex
jobs map[string]time.Duration
wg sync.WaitGroup
}
// Do a job.
func (jwg *JobWaitGroup) Do(name string, fn func()) {
jwg.lock.Lock()
defer jwg.lock.Unlock()
if jwg.jobs == nil {
jwg.jobs = make(map[string]time.Duration)
}
if _, dup := jwg.jobs[name]; dup {
panic(fmt.Sprintf("job %q already exists", name))
}
jwg.jobs[name] = -1
jwg.wg.Add(1)
start := time.Now()
go func() {
defer func() {
jwg.lock.Lock()
defer jwg.lock.Unlock()
jwg.jobs[name] = time.Now().Sub(start)
jwg.wg.Done()
}()
fn()
}()
}
// Wait for all jobs to finish, and return how long each job took.
func (jwg *JobWaitGroup) Wait() map[string]time.Duration {
jwg.wg.Wait()
return jwg.jobs
}
// Status returns the total number of jobs that have been started, and
// a list of still-running jobs.
func (jwg *JobWaitGroup) Status() (int, []string) {
jwg.lock.RLock()
n := len(jwg.jobs)
var jobs []string
for job, duration := range jwg.jobs {
if duration < 0 {
jobs = append(jobs, job)
}
}
defer jwg.lock.RUnlock()
sort.Strings(jobs)
return n, jobs
}
|