/
main.go
88 lines (67 loc) · 1.6 KB
/
main.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
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"runtime/pprof"
"sync"
"time"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
var (
messageCh chan string
duration time.Duration
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
start := time.Now()
ctx, cancel := context.WithTimeout(context.TODO(), duration)
timeNow := time.Now()
ctxElapsed := timeNow.Sub(start)
//ctx, cancel := context.WithDeadline(ctx, deadline)
defer cancel()
select {
case <-ctx.Done():
if ctx.Err() == context.DeadlineExceeded {
timeNow = time.Now()
elapsed := timeNow.Sub(start)
messageCh <- fmt.Sprintf("worker %v context error: %v, context diff in time: %v time creating context: %v\n", id, ctx.Err(), elapsed, ctxElapsed)
}
default:
// NOOP fmt.Printf("Worker %d done\n", id)
}
}
func main() {
parallelism := flag.Int("parallelism", 10000, "number of workers to spawn")
profile := flag.String("profile", "", "where to save CPU profile. no profile is taken if empty")
flag.DurationVar(&duration, "worker-timeout", time.Millisecond, "")
flag.Parse()
if *profile != "" {
f, err := os.Create(*profile)
check(err)
defer f.Close()
check(pprof.StartCPUProfile(f))
defer pprof.StopCPUProfile()
}
messageCh = make(chan string, *parallelism)
start := time.Now()
wg := sync.WaitGroup{}
for i := 1; i <= *parallelism; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
close(messageCh)
timeNow := time.Now()
elapsed := timeNow.Sub(start)
for msg := range messageCh {
fmt.Print(msg)
}
fmt.Printf("time elapsed of the full program: %v\n", elapsed)
}