-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
48 lines (40 loc) · 1.13 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main
import (
"fmt"
"sync"
)
// the number of the consumers +1, because a real programmer start to count from zero :)
const N int = 9+1
func producer(chList [N]chan []int){
// create a matrix of data, every row matches a consumer
var dataSend [N][]int
for i:=0;i<(N*N);i++ {
// a tricky way to assign every row for each consumer
dataSend[i%N] = append(dataSend[i%N], i)
}
// send data to a specific part of the array that matches the producer
for i:=0;i<N;i++ {
chList[i] <- dataSend[i]
}
}
func consumer(chList [N]chan []int, wg *sync.WaitGroup,i int){
defer wg.Done()
fmt.Printf("consumer%d value: %d\n", i, <-chList[i])
}
func main(){
wg := sync.WaitGroup{}
// I prefer to use a array of channel because do that every process has own
var chList [N]chan []int
// you have to initialize channels inside the channel array, to avoid nil value
for i := range chList {
chList[i] = make(chan []int)
}
go producer(chList)
// launch n consumers
for i:=0;i<N;i++ {
wg.Add(1)
go consumer(chList, &wg, i)
}
// wait only consumers because the program only need to wait that every channel are consumed
wg.Wait()
}