gpt4 book ai didi

go - channel 中的元素数

转载 作者:IT老高 更新时间:2023-10-28 12:58:00 29 4
gpt4 key购买 nike

使用缓冲 channel ,如何测量 channel 中有多少元素?例如,我正在这样的 channel 上创建和发送:

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

我想测量 channel send_ch 中有多少 msgs

我知道,由于并发性,测量不会准确,因为在测量和操作之间可能会发生抢占(例如,在此视频中讨论 Google I/O 2012 - Go Concurrency Patterns)。我将使用它来控制生产者和消费者之间的流量,即,一旦我通过了高水位线,就会改变一些行为,直到我通过低水位线。

最佳答案

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

将输出:

34

关于go - channel 中的元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003749/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com