上下文因超时而取消,但计算未中止?



试图理解go上下文取消将如何中止后续代码的执行

实验详情:

  1. 主函数具有在2sec中超时的上下文
  2. Main func
  3. 在单独的 go-routine 中调用另一个 funcsum- 该例程休眠1sec用于测试运行-1 和4sec用于测试运行-2
  4. 让主休眠3sec让旋转例程完成执行
package main
import (
"context"
"fmt"
"log"
"time"
)
func main() {
c := context.Background()
childCtx, cancel := context.WithTimeout(c, 2*time.Second)
defer cancel()
ch := make(chan int, 1)
go sum(5, 6, ch)
var msg string
select {
case <-childCtx.Done():
msg = "return from ctx done channel"
case res := <-ch:
msg = fmt.Sprintf("return from go routine: %v", res)
}
log.Print(msg)
time.Sleep(3 * time.Second) //sleeping here to test if go-routine is still running
}

func sum(x int, y int, c chan<- int) {
time.Sleep(1 * time.Second) 
//testcase-1: sleep - 1s
//testcase-2: sleep - 4s
result := x + y
log.Printf("print from sum fn: %v", result)
c <- result
}

测试用例 1 的响应:睡眠和函数 1 秒:

2021/04/12 01:06:58 print from sum fn: 11
2021/04/12 01:06:58 return from go routine: 11

测试用例-2 的响应:睡眠和函数 4 秒:

2021/04/12 01:08:25 return from ctx done channel
2021/04/12 01:08:27 print from sum fn: 11

在 testcase-2 中,当 sum func 休眠 4 秒时,上下文已经在 2 秒后被超时取消,为什么它仍然在 diff go-routine 中执行 sum func 并打印print from sum fn: 1

来自文档:取消此上下文会释放与其关联的资源。

我的假设是所有计算将在 2 秒后立即中止,包括旋转的 go-routine

。让我知道如何做对这件事,谢谢

正如@AndySchweig所指出的,context表示取消事件,但不强制取消。任何可能阻塞的 goroutine 都可以在检测到取消后尽最大努力尝试取消/清理。

要更新sum功能以支持取消,您可以尝试:

// add context parameter as the first argument
// add a return error - to indicate any errors (i.e. function was interrupted due to cancelation)
func sum(ctx context.Context, x int, y int, c chan<- int) (err error) {
wait := 1 * time.Second // testcase-1
//wait := 4 * time.Second // testcase-2
// any blocking called - even sleeps - should be interruptible
select {
case <-time.After(wait):
case <-ctx.Done():
err = ctx.Err()
return
}
result := x + y
log.Printf("print from sum fn: %v", result)
select {
case c <- result:
case <-ctx.Done(): // check for ctx cancelation here - as no one may be listening on result channel
err = ctx.Err()
}
return
}

https://play.golang.org/p/DuIACxPvHYJ

上下文不会中止 go 例程。在您的情况下,如果上下文的时间已结束,您只是不会打印 go 例程的结果。go 例程对上下文一无所知。

最新更新