
context 执行 cancel,但 <- ctx.done() 没执行?
在 go 中使用 context 包时,遇到一个问题:执行了 ctx.done() 取消了 context,但 goroutine 中的 <- ctx.done() 却没有执行,这导致程序无法正常退出。
这个问题的本质是阻塞在 channel 写入操作上。在给出的代码示例中,goroutine 的 select 语句阻塞在 ch <- n 中:
for {
select {
case <-ctx.done():
fmt.println("done")
default:
n += 1
ch <- n
}
}当执行 cancel() 取消 context 时,虽然 ctx.done() 返回了,但此时 goroutine 仍然阻塞在 ch <- n 中,因此不会执行 <- ctx.done()。
要解决这个问题,一种方法是关闭 channel,以指示 goroutine 终止:
for {
select {
case <-ctx.Done():
fmt.Println("done")
close(ch) // 关闭 channel
return
default:
n += 1
ch <- n
}
}关闭 channel 后,range 遍历会结束,goroutine 也能正常退出。
以上就是Go 中使用 context 包时,执行 Cancel 后的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号