dsn46282 2012-10-22 00:56
浏览 52
已采纳

通道中的元素数

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条回答 默认 最新

  • dongziche8030 2012-10-22 01:10
    关注

    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.
    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题