-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
101 lines (89 loc) · 2.07 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
89
90
91
92
93
94
95
96
97
98
99
100
101
package main
import (
"context"
"log"
"os"
"syscall"
"time"
_ "net/http/pprof"
"runtime/trace"
"github.com/x-mod/routine"
)
func prepare(ctx context.Context) error {
log.Println("prepare begin")
defer log.Println("prepare end")
trace.Logf(ctx, "prepare", "prepare ... ok")
return nil
}
func cleanup(ctx context.Context) error {
log.Println("cleanup begin")
defer log.Println("cleanup end")
time.Sleep(time.Millisecond * 50)
trace.Logf(ctx, "cleanup", "cleanup ... ok")
return nil
}
func foo(ctx context.Context) error {
log.Println("foo begin")
defer log.Println("foo end")
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(3 * time.Second):
trace.Logf(ctx, "foo", "sleeping 3s done")
return nil
}
}
func bar(ctx context.Context) error {
log.Println("bar begin")
defer log.Println("bar end")
for i := 0; i < 10; i++ {
log.Println(i)
trace.Logf(ctx, "bar", "counting ... %d", i)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(10 * time.Second):
return nil
}
}
func app(ctx context.Context) error {
log.Println("app begin")
defer log.Println("app end")
ch := routine.Child(ctx, routine.ExecutorFunc(func(ctx context.Context) error {
log.Println("append go ... begin")
<-time.After(10 * time.Second)
log.Println("append go ... end")
return nil
}))
<-ch
return nil
}
func main() {
f, err := os.Create("trace.out")
if err != nil {
log.Fatalf("failed to create trace output file: %v", err)
}
defer func() {
if err := f.Close(); err != nil {
log.Fatalf("failed to close trace file: %v", err)
}
}()
ctx, cancel := context.WithCancel(context.TODO())
if err := routine.Main(
ctx,
routine.ExecutorFunc(bar),
routine.Signal(syscall.SIGINT, routine.SigHandler(func() {
cancel()
})),
routine.Prepare(routine.ExecutorFunc(prepare)),
routine.Cleanup(routine.ExecutorFunc(cleanup)),
routine.Trace(f),
routine.Go(routine.ExecutorFunc(app)),
routine.Go(routine.ExecutorFunc(foo)),
routine.Go(routine.ExecutorFunc(foo)),
routine.Go(routine.ExecutorFunc(foo)),
); err != nil {
log.Println(err)
}
}