对于这样的代码:
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
还在执行,并没有被马上中断。