Skip to content

Commit 850bc96

Browse files
committed
groutine原理
1 parent fae5acd commit 850bc96

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

main/main.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"time"
7+
)
8+
9+
func main() {
10+
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
11+
defer cancel()
12+
13+
go handle(ctx, 500*time.Millisecond)
14+
select {
15+
case <-ctx.Done():
16+
fmt.Println("main", ctx.Err())
17+
}
18+
}
19+
20+
func handle(ctx context.Context, duration time.Duration) {
21+
select {
22+
case <-ctx.Done():
23+
fmt.Println("handle", ctx.Err())
24+
case <-time.After(duration):
25+
fmt.Println("process request with", duration)
26+
}
27+
}

0 commit comments

Comments
 (0)