为什么这个函数没有取消?

huangapple go评论80阅读模式
英文:

Why isn't this function cancelling?

问题

我有一段简单的代码,但由于某种原因,上下文没有取消函数。希望能得到一些帮助!

package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
  ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  defer cancel()

  test(ctx)
}

func test(ctx context.Context) {
  select {
  case <-ctx.Done():
    return

  default:
    time.Sleep(time.Second)
  }

  fmt.Println("Starting print")
  time.Sleep(100 * time.Second)
  fmt.Println("Ending print")
}

请帮我翻译这段代码。

英文:

I have a simple piece of code, but for some reason the context is not cancelling the function. Some help would be much appreciated!

package main

import (
	&quot;context&quot;
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
  ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
  defer cancel()

  test(ctx)
}

func test(ctx context.Context) {
  select {
  case &lt;-ctx.Done():
    return

  default:
    time.Sleep(time.Second)
  }

  fmt.Println(&quot;Starting print&quot;)
  time.Sleep(100 * time.Second)
  fmt.Println(&quot;Ending print&quot;)
}

</details>


# 答案1
**得分**: 2

选择语句执行默认子句因为上下文没有被取消当上下文被取消时不会中断默认子句

使用以下代码实现可取消的休眠

```go
select {
case <-ctx.Done():
  return
case <-time.After(time.Second):
}
英文:

The select statement executes the default clause because the context is not canceled. The default clause is not interrupted when the context canceled.

Use this code to implement a cancelable sleep:

select {
case &lt;-ctx.Done():
  return
case &lt;-time.After(time.Second):
}

huangapple
  • 本文由 发表于 2023年4月23日 23:39:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76085779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定