Is there a way to find out how many messages are in the channel buffer?

I have identified a bottleneck in my program, this is a buffer channel. I would like to give the client an indication of system loading, which should be indicated by the number of messages buffered in the channel.

Is there a way in Go to indicate how many buffered messages are in the channel?

If you also have a Java background, I'm looking for the equivalent of this: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html#size ()

+4
source share
2 answers

Length and capacity

The built-in functions len and cap accept arguments of various types and return a result of type int . The implementation ensures that the result always fits into an int .

 Call Argument type Result len(s) chan T number of elements queued in channel buffer cap(s) chan T channel buffer capacity 

The len function for a channel gives the number of items queued in the channel buffer. For instance,

 package main import "fmt" func main() { ch := make(chan int, 8) ch <- 42 ch <- 7 <-ch ch <- 64 // number of queued elements = 1 + 1 - 1 + 1 = 2 fmt.Println(len(ch), cap(ch)) } 

Output:

 2 8 
+11
source

There is an alternative solution for this, using the "queue" process, which processes the message queue and can also report its size. To do this, you will need an input channel and an output channel, as well as a request channel through which the size will be obtained. Since there will be two input channels, you will need a choice (CSP selection) between them.

Here's a little demonstration of this in action. The queue consists of a slice as a buffer and an input channel.

 func queue(in <-chan string, out chan<- string, query <-chan chan int) { buffer := []string{} var s string var reply chan int for { // Go select doesn't support boolean guards so we need the 'if' outside the select instead if len(buffer) > 0 { select { case reply = <-query: reply <- len(buffer) case s = <-in: buffer = append(buffer, s) case out <- buffer[0]: buffer = buffer[1:] } } else { select { case reply = <-query: reply <- len(buffer) case s = <-in: buffer = append(buffer, s) } } } } 
-1
source

Source: https://habr.com/ru/post/1485350/


All Articles