How to allocate an array of channels

2020-05-30 03:23发布

问题:

How to create an array of channels?

For example: replace the following five lines with an array of channels, with a size of 5:

var c0 chan int = make(chan int);
var c1 chan int = make(chan int);
var c2 chan int = make(chan int);
var c3 chan int = make(chan int);
var c4 chan int = make(chan int);

回答1:

The statement var chans [5]chan int would allocate an array of size 5, but all the channels would be nil.

One way would be to use a slice literal:

var chans = []chan int {
   make(chan int),
   make(chan int),
   make(chan int),
   make(chan int),
   make(chan int),
}

If you don't want to repeat yourself, you would have to iterate over it and initialize each element:

var chans [5]chan int
for i := range chans {
   chans[i] = make(chan int)
}


回答2:

I think you can use buffered channels in this case.

Channels can be buffered. Provide the buffer length as the second argument to make to initialize a buffered channel:

ch := make(chan int, 5)

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.

https://tour.golang.org/concurrency/3