gpt4 book ai didi

go - 仔细检查 Go 的 select 语句

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:03 26 4
gpt4 key购买 nike

我正在学习 Golang,看完后this post在 Go 的博客上,我有以下问题。

我从以下代码开始(来自帖子):

select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
}

并且基于什么A Tour of Go状态:

... It chooses one at random if multiple are ready.

据我了解,可以在准备好结果的同时超时。我的问题是在默认情况下仔细检查是否值得(或正确)。

类似下面的内容:

select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out

// So check ch one last time
select {
case <-ch:
// a read from ch has occurred at same time of a timeout,
// so ignore the timeout
default:
// definitive timeout
}
}

最佳答案

如果其中一个 channel 发生超时,则您的工作完成和超时同时触发的几率非常小,因此没有必要考虑。

声明“...如果多个准备就绪,它会随机选择一个。”当你确实有一个可行的理由发生这种情况时适用 - 例如,当你在多个作业 channel 上有一个选择案例时,你正在使用单个 goroutine 处理。

关于go - 仔细检查 Go 的 select 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48154800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com