通道中的元素数量

huangapple go评论87阅读模式
英文:

Number of elements in a channel

问题

使用缓冲通道,如何测量通道中有多少元素?例如,我正在创建和发送一个通道,如下所示:

send_ch := make(chan []byte, 100)
// 代码
send_ch <- msg

我想测量通道send_ch中有多少个msg

我知道由于并发性,测量结果不会是精确的,因为在测量和操作之间可能会发生抢占(例如在这个视频中讨论的Google I/O 2012 - 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 &lt;- 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

得分: 203

http://golang.org/pkg/builtin/#len

> func len(v Type) int
> len内置函数根据其类型返回v的长度:
>
> - 数组:v中的元素数量。
> - 指向数组的指针:*v中的元素数量(即使v为nil)。
> - 切片或映射:v中的元素数量;如果v为nil,则len(v)为零。
> - 字符串:v中的字节数。
> - 通道:通道缓冲区中排队(未读取)的元素数量;如果v为nil,则len(v)为零。

<!-- language-all: Go -->

package main

import &quot;fmt&quot;

func main() {
        c := make(chan int, 100)
        for i := 0; i &lt; 34; i++ {
                c &lt;- 0
        }
        fmt.Println(len(c))
}

将输出:

34
英文:

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.

<!-- language-all: Go -->

package main

import &quot;fmt&quot;

func main() {
        c := make(chan int, 100)
        for i := 0; i &lt; 34; i++ {
                c &lt;- 0
        }
        fmt.Println(len(c))
}

will output:

34

答案2

得分: 0

获取正在发送的缓冲通道的长度的方法是:

	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))
英文:

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 &lt; 3; i++ {
			ch1 &lt;- &quot;hello&quot;
		}
		done &lt;- true
	}()

	&lt;-done
	fmt.Println(len(ch1))

huangapple
  • 本文由 发表于 2012年10月22日 08:56:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/13003749.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定