Go 中为什么需要等待 select?

问题描述 投票:0回答:1

我刚刚学习在上下文中取消。 这是我的代码。

package main

import (
  "fmt"
  "context"
)

func main() {
  ctx := context.Background()

  do(ctx)
}

func do(ctx context.Context) {
  ctx, ctxCancel := context.WithCancel(ctx)

  resultCh := make(chan string)

  go terminate(ctx, resultCh)

  resultCh <- "value1"
  resultCh <- "value2"

  fmt.Println("pre cancel")

  ctxCancel()

  fmt.Println("post cancel")
}

func terminate(ctx context.Context, ch <-chan string) {
  for {
    select {
    case <-ctx.Done():
      fmt.Println("terminate")
      return
    case result := <-ch:
      fmt.Println(result)
    }
  }
}

想问

为什么会这样。 我需要什么知识?

我期待输出。

但得到的实际输出不包括“终止”。

value1
value2
pre cancel
terminate
post cancel

固定代码

我在取消功能下添加了 time.Sleep 。 然后输出就是我的预期。

ctxCancel()
time.Sleep(100 * time.Millisecond) // add
go goroutine
1个回答
0
投票

据我了解,使用 select 背后的核心思想是等到至少一种情况“准备好”。我在下面提供了一个示例,可能会有所帮助。这里 select 用于等待从通道 ch 接收值或发生 1 秒超时。

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int)

    go func() {
        // Simulate some time-consuming operation
        time.Sleep(2 * time.Second)
        ch <- 42
    }()

    select {
    case result := <-ch:
        fmt.Println("Received result:", result)
    case <-time.After(1 * time.Second):
        fmt.Println("Timeout reached")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.