英文:
Number of elements in a channel
问题
使用缓冲通道,如何测量通道中有多少元素?例如,我正在创建和发送一个通道,如下所示:
send_ch := make(chan []byte, 100)
// 代码
send_ch <- msg
我想测量通道send_ch中有多少个msg。
我知道由于并发性,测量结果不会是精确的,因为在测量和操作之间可能会发生抢占(例如在这个视频中讨论的Google I/O 2012 - Go并发模式)。我将在生产者和消费者之间使用这个来进行流量控制,即一旦我通过了一个高水位标记,就会改变一些行为,直到我再次通过一个低水位标记。
英文:
Using a buffered channel, how do measure how many elements are in the channel? For example, I'm creating and sending on a channel like this:
send_ch := make(chan []byte, 100)
// code
send_ch <- msg
I want to measure how many msgs are in the channel send_ch.
I'm aware that due to concurrency the measurement won't be exact, as pre-emption could occur between measurement and action (eg discussed in this video Google I/O 2012 - Go Concurrency Patterns). I'll be using this for flow control between producers and consumers ie once I've passed through a high watermark, changing some behaviour until I pass back through a low watermark.
答案1
得分: 203
http://golang.org/pkg/builtin/#len
> func len(v Type) int
> len内置函数根据其类型返回v的长度:
>
> - 数组:v中的元素数量。
> - 指向数组的指针:*v中的元素数量(即使v为nil)。
> - 切片或映射:v中的元素数量;如果v为nil,则len(v)为零。
> - 字符串:v中的字节数。
> - 通道:通道缓冲区中排队(未读取)的元素数量;如果v为nil,则len(v)为零。
<!-- language-all: Go -->
package main
import "fmt"
func main() {
c := make(chan int, 100)
for i := 0; i < 34; i++ {
c <- 0
}
fmt.Println(len(c))
}
将输出:
34
英文:
http://golang.org/pkg/builtin/#len
> func len(v Type) int
> The len built-in function returns the length of v, according to its type:
>
> - Array: the number of elements in v.
> - Pointer to array: the number of elements in *v (even if v is nil).
> - Slice, or map: the number of elements in v; if v is nil, len(v) is zero.
> - String: the number of bytes in v.
> - Channel: the number of elements queued (unread) in the channel buffer; if v is nil, len(v) is zero.
<!-- language-all: Go -->
package main
import "fmt"
func main() {
c := make(chan int, 100)
for i := 0; i < 34; i++ {
c <- 0
}
fmt.Println(len(c))
}
will output:
34
答案2
得分: 0
获取正在发送的缓冲通道的长度的方法是:
done := make(chan bool)
ch1 := make(chan string, 3)
go func() {
for i := 0; i < 3; i++ {
ch1 <- "hello"
}
done <- true
}()
<-done
fmt.Println(len(ch1))
英文:
To get the length of a buffered channel that is sending in a go routine:
done := make(chan bool)
ch1 := make(chan string, 3)
go func() {
for i := 0; i < 3; i++ {
ch1 <- "hello"
}
done <- true
}()
<-done
fmt.Println(len(ch1))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论