Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of elements in a channel

Tags:

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.

like image 752
Sonia Hamilton Avatar asked Oct 22 '12 00:10

Sonia Hamilton


People also ask

How to check length of channel in Golang?

In Golang, len function is used to find the length of a channel, pointer, slice, string, and map.

What is channel size in Golang?

First off, the maximum message size (or channel type) is 2^16 bytes, or 64 kilobytes.

What is the difference between a buffered channel and an unbuffered channel?

When a channel is created with no capacity, it is called an unbuffered channel. In turn, a channel created with capacity is called a buffered channel.

Can we use for range through a channel?

The range keyword can also be used on a channel. By doing so, it will iterate over every item thats send on the channel. You can iterate on both buffered and unbuffered channels, but buffered channels need to be closed before iterating over them.


1 Answers

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 
like image 193
Artem Shitov Avatar answered Sep 18 '22 08:09

Artem Shitov