-
Notifications
You must be signed in to change notification settings - Fork 22
/
main.go
49 lines (40 loc) · 824 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
package main
import (
"context"
"fmt"
"time"
)
func main() {
Sample("WithTimeout", WithTimeout)
Sample("WithCancel", WithCancel)
}
func WithTimeout() {
// This context will be canceled after 100ms timeout
ctx, cancelFn := context.WithTimeout(context.Background(), 100 * time.Millisecond)
defer cancelFn()
select {
case <-time.After(1 * time.Minute):
break
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
func WithCancel() {
ctx, cancelFn := context.WithCancel(context.Background())
go func() {
time.Sleep(100 * time.Millisecond)
// This function will cancel the context after 100ms sleep
cancelFn()
}()
select {
case <-time.After(1 * time.Minute):
break
case <-ctx.Done():
fmt.Println(ctx.Err())
}
}
func Sample(name string, fn func()) {
fmt.Println(">", name)
fn()
fmt.Println()
}