我制作了这个简单的代码,尝试知道通道是如何工作的,如果在发送通道b之后发送通道c,则不会发送最后一个例程中的通道,
我有2个通道,通道c用于将通道b拆分为4个切片。
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)
}
答案 0 :(得分:3)
bucket := make(chan []int)
您的b
频道的容量为0.这意味着无论何时向此频道发送内容,频道都会立即满,并会阻止直到接收方读取该频道。
当只剩下一个跑步者时,没有人会打电话bucket := <-b
来读取最后一个桶,因此最后一个goroutine永远停留在b <- bucket
行,因此下一行{ <1}}永远不会被称为最后一个goroutine。