对于这样的代码:
package main
import (
"context"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UnixNano())
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
Run(ctx)
}
func Run(ctx context.Context) {
}
func SlowOperation() {
n := rand.Intn(3)
time.Sleep(time.Duration(n) * time.Second)
}要求仅编辑 Run 函数,实现:
Run必须要调用SlowOperation函数Run函数在ctx超时后必须立刻返回- 如果
SlowOperation结束的比ctx快,也立刻返回
进阶问题:
有什么场景适合使用这段代码吗?
一个服务在接受请求时可能会调用多个服务,但它的也需要控制整体的时间消耗。它需要用这种写法来实现。
这段代码有什么不足之处?
假如
ctx 超时导致 Run 返回,此时 SlowOperation 还在执行,并没有被马上中断。