context的使用
package main
import "fmt"
import (
"context"
"time"
)
func inc(a int) int {
res := a+1
time.Sleep(1*time.Second)
return res
}
func Add(ctx context.Context,a,b int) int {
res := 0
for i:=0;i<a;i++{
res = inc(res)
select {
case <- ctx.Done():
return -1
default:
}
}
for i:=0;i<b;i++{
res = inc(res)
select {
case <- ctx.Done():
return -1
default:
}
}
return res
}
func main() {
{
a:=1
b:=2
timeout := 3*time.Second
ctx, _ := context.WithTimeout(context.Background(),timeout)
res := Add(ctx,a,b)
fmt.Printf("Compute %d+%d,result:%d",a,b,res)
}
{
a:=1
b:=2
ctx,cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(1*time.Second)
cancel()
fmt.Printf("error:%s", ctx.Err())
}()
res := Add(ctx,1,2)
fmt.Printf("Compute %d+%d,result:%d",a,b,res)
}
}
返回
Compute 1+2,result:-1error:context canceled
Compute 1+2,result:-1