英文:
Is there any way to check if values are buffered in a Go chan?
问题
我该如何实现类似以下的功能?:
func foo(input <-chan char, output chan<- string) {
var c char
var ok bool
for {
if input中有缓冲值 {
c, ok = <-input
} else {
output <- "更新消息"
c, ok = <-input
}
对c和ok进行操作
}
}
基本上,我想要检查通道中是否有缓冲值,以便在线程被阻塞之前,如果没有缓冲值,我可以发送一条更新消息。
英文:
How can I do something like the following?:
func foo(input <-chan char, output chan<- string) {
var c char
var ok bool
for {
if ThereAreValuesBufferedIn(input) {
c, ok = <-input
} else {
output <- "update message"
c, ok = <-input
}
DoSomethingWith(c, ok)
}
}
Basically, I want to check if there are buffered values in the chan so that if there aren't, I could send an update message before the thread is blocked.
答案1
得分: 3
是的,这就是select
调用允许你做的事情。它可以让你检查一个或多个通道是否准备好读取值。
英文:
Yes, this is what the select
call allows you to do. It will enable you to check one or more channels for values ready to be read.
答案2
得分: 3
package main
func foo(input <-chan char, output chan<- string) {
for {
select {
case c, ok := <-input:
if ok { // ThereAreValuesBufferedIn(input)
... process c
} else { // input is closed
... handle closed input
}
default:
output <- "update message"
c, ok := <-input // will block
DoSomethingWith(c, ok)
}
}
}
英文:
package main
func foo(input <-chan char, output chan<- string) {
for {
select {
case c, ok := <-input:
if ok { // ThereAreValuesBufferedIn(input)
... process c
} else { // input is closed
... handle closed input
}
default:
output <- "update message"
c, ok := <-input // will block
DoSomethingWith(c, ok)
}
}
}
EDIT: Fixed scoping bug.
答案3
得分: 1
其他人已经回答了你关于代码的问题(使用select
),但为了完整起见,并回答你问题标题中特定的问题(“有没有办法检查Go通道中的值是否已缓冲?”),len
和cap
内置函数在缓冲通道上的工作方式与预期相同(len
返回缓冲元素的数量,cap
返回通道的最大容量)。
http://tip.golang.org/ref/spec#Length_and_capacity
英文:
Others have answered your question for what you wanted to do with your code (use a select
), but for completeness' sake, and to answer the specific question asked by your question's title ("Is there any way to check if values are buffered in a Go chan?"), the len
and cap
built-in functions work as expected on buffered channels (len
returns the number of buffered elements, cap
returns the maximum capacity of the channel).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论