0%

context 超时处理

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
package main

import (
"context"
"fmt"
"time"
)

func main() {
ctx, cancel := context.WithTimeout(context.TODO(), time.Second*3)
defer cancel()
go task(ctx)
time.Sleep(time.Second * 10)
}

func task(ctx context.Context) {
ch := make(chan struct{}, 0)
go func() {
// 模拟4秒耗时任务
time.Sleep(time.Second * 4)
ch <- struct{}{}
}()
select {
case <-ch:
fmt.Println("done")
case <-ctx.Done():
fmt.Println("timeout")
}
}