-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (53 loc) · 989 Bytes
/
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
package main
import (
"context"
"fmt"
"math/rand"
"os"
"runtime/trace"
"time"
)
/*
1. 只能编辑 foo 函数
2. foo 必须要调用 slow 函数
3. foo 函数在 ctx 超时后必须立刻返回
4. 【加分项】如果 slow 结束的比 ctx 快,也立刻返回
*/
func main() {
f, err := os.Create("trace.out")
if err != nil {
panic(err)
}
defer f.Close()
err = trace.Start(f)
if err != nil {
panic(err)
}
defer trace.Stop()
rand.Seed(time.Now().UnixNano())
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
foo(ctx)
fmt.Println("Done")
}
func foo(ctx context.Context) {
ch := make(chan struct{}, 1)
go func() {
slow()
ch <- struct{}{}
}()
select {
case <-ctx.Done():
fmt.Println("Main Context Time out")
return
case <-ch:
fmt.Println("The Slow function Done")
return
}
}
func slow() {
n := rand.Intn(3)
time.Sleep(time.Duration(n) * time.Second)
fmt.Printf("sleep %ds\n", n)
}