Sonia Hamilton
Sonia Hamilton

Reputation: 4419

Number of elements in a channel

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.

Upvotes: 122

Views: 101949

Answers (2)

OctaviaLo
OctaviaLo

Reputation: 1396

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))

Upvotes: 0

Artem Shitov
Artem Shitov

Reputation: 2969

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

Upvotes: 211

Related Questions