How to allocate an array of channels

别说谁变了你拦得住时间么 提交于 2019-12-03 16:12:47

问题


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



来源:https://stackoverflow.com/questions/2893004/how-to-allocate-an-array-of-channels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!