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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。