dongwo8827523 2017-04-18 20:42
浏览 32

在Go中访问频道长度的正确方法

I have been using Go for a little and still getting better everyday, but not an expert per se. Currently I am tackling concurrency and goroutines as I think that is the final unknown in my Go toolbelt. I think I am getting the hang of it as such, but still definitely a beginner.

The task I am having an issue with seems pretty basic to me, but nothing I have tried works. I would like to figure out a way to calculate the length of a channel.

From what I have gathered, len() only works on buffered channels so that won't help me in this case. What I am doing is reading values from the DB in batches. I have a generator func that goes like

func gen() chan Result {
  out := make(chan Result)

  go func() {
    ... query db
    for rows.Next() {
      out <- row
    }
     close(out)
   }()

  return out
}

then I am using it as such

c := gen()

...

// do other stuff

I would either like to return the count with the out channel, or wrap all of it in a struct type and just return that.

like so:

c, len := gen()

or:

a := gen()

fmt.Println(a.c)
fmt.Println(a.len)

I believe I have tried all but using atomic, which I think would actually work but I read around and it apparently isn't the right thing to use atomic for. What other options do I have that either don't leave me with a 0 or blocks infinitely

Thanks!

  • 写回答

2条回答 默认 最新

  • drema2014 2017-04-18 21:09
    关注

    The len built-in will return the "length" of a channel:

    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.

    But I don't think that will help you.

    What you really need is a new approach to your problem: counting the items in queue in a channel is not an appropriate way to handle "batches" of tasks.

    What do you need this length for?

    评论

报告相同问题?