开发者

How to allocate an array of channels

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 cha开发者_开发技巧n int = make(chan int);


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


c := make(map[int]chan int)
for i := 1; i <= 5; i++ {
    c[i] = make(chan int)
}
for _,v := range c {
    fmt.Println(v)
}

You can create like that, use slice and channel


Example for []chan[]string. it can be extended for all type of cases.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var ch [4]chan []string
    for i := range ch {
        ch[i] = make(chan []string, 1)
    }

    ch1 := []string{"this", "that", "who"}

    ch2 := []string{"one", "two", "three"}

    ch3 := []string{"four", "five", "six"}

    ch4 := []string{"seven", "eight", "nine"}

    wg := sync.WaitGroup{}

    wg.Add(1)
    for i := 0; i < 4; i++ {
        switch i {
        case 0:
            ch[i] <- ch1
        case 1:
            ch[i] <- ch2
        case 2:
            ch[i] <- ch3
        case 3:
            ch[i] <- ch4
        default:
        }
    }
    wg.Done()

    for i := 0; i < 4; i++ {
        fmt.Println(<-ch[i])

    }
    wg.Wait()
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜