I made this simple code, trying to know how's channel works, somehow if channel c is sent after channel b is sent, channel in last routine is not being sent,
I have 2 channel, channel c is for spliting channel b to 4 part of slice.
package main
import (
"fmt"
"strconv"
)
func runner(idx int, c chan []int, b chan []int) {
var temp []int
fmt.Println("runner " + strconv.Itoa(idx))
bucket := <-b
for k, v := range bucket {
if v != 0 {
temp = append(temp, v)
bucket[k] = 0
}
if len(temp) == 5 {
break
}
}
//Strange condition if channel c is sent after channel b is sent,
//somehow the last chan is not being sent
b <- bucket
c <- temp
//this is right if channel b is sent after channel c is sent
//c <- temp
//b <- bucket
}
func printer(c chan []int) {
for {
select {
case msg := <-c:
fmt.Println(msg)
//time.Sleep(time.Second * 1)
}
}
}
func main() {
c := make(chan []int, 5)
bucket := make(chan []int)
go runner(1, c, bucket)
go runner(2, c, bucket)
go runner(3, c, bucket)
go runner(4, c, bucket)
bucket <- []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
go printer(c)
var input string
fmt.Scanln(&input)
}
bucket := make(chan []int)
Your b
channel's capacity is 0. This means whenever you send something to this channel, the channel is full immediately and will block until a receiver reads the channel.
When there is only one runner left, no one is going to call bucket := <-b
to read the last bucket, thus this last goroutine is stuck forever on the b <- bucket
line, and thus the next line c <- temp
will never be called for this last goroutine.