记录 golang context
有四种
context.WithCancel
context.WithDeadline
context.WithTimeout(context.Background(), 2 * time.Second)
- 设置超时的context,也返回
ctx
和 cancel
,可以等待自动超时,也可以提前执行cancel
,ctx.Done
都可以接收到值
context.WithValue
WithCancel示例
Fold code blockGO
Copy code
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
| package main
import ( "context" "fmt" "sync" "time" )
var wg sync.WaitGroup
func cpuInfo(ctx context.Context) { defer wg.Done()
ctx2, _ := context.WithCancel(ctx) go memoryInfo(ctx2)
for { select { case <-ctx.Done(): fmt.Println("==> 退出CPU监控") return default: time.Sleep(time.Second) fmt.Println("获取CPU信息") } } }
func memoryInfo(ctx context.Context) { defer wg.Done() for { select { case <-ctx.Done(): fmt.Println("==> 退出内存监控") return default: time.Sleep(time.Second) fmt.Println("获取内存信息") } } }
func main() { ctx, cancel := context.WithCancel(context.Background()) wg.Add(2) go cpuInfo(ctx)
time.Sleep(time.Second * 5)
cancel()
wg.Wait()
}
|
输出
Fold code block
Copy code
1 2 3 4 5 6 7 8 9 10 11 12
| 获取内存信息 获取CPU信息 获取CPU信息 获取内存信息 获取内存信息 获取CPU信息 获取CPU信息 获取内存信息 获取CPU信息 ==> 退出CPU监控 获取内存信息 ==> 退出内存监控
|
WithTimeout示例
Fold code blockGO
Copy code
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
| package main
import ( "context" "fmt" "sync" "time" )
var wg sync.WaitGroup
func cpuInfo(ctx context.Context) { defer wg.Done()
for { select { case <-ctx.Done(): fmt.Println("==> 退出CPU监控") return default: time.Sleep(time.Second) fmt.Println("获取CPU信息") } } }
func main() { ctx, _ := context.WithTimeout(context.Background(), time.Second*3)
wg.Add(1) go cpuInfo(ctx)
wg.Wait() }
|
输出
Fold code block
Copy code
1 2 3 4
| 获取CPU信息 获取CPU信息 获取CPU信息 ==> 退出CPU监控
|