我刚刚学习在上下文中取消。 这是我的代码。
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
据我了解,使用 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")
}
}