迭代 golang 无缓冲通道时,我遇到了一个令人困惑的输出。通道定义为chan []int。然后我将两个切片推送到通道,[0 1] 和 [2 3]。但是当我从频道中获取元素时,我得到了 [2 3] 和 [2 3]。为什么会这样?
package main
import "fmt"
import "sync"
func producer(jobs chan []int, wg *sync.WaitGroup) {
defer wg.Done()
a := make([]int, 2)
index := 0
for i := 0; i < 4; i++ {
a[index] = i
index++
if index == 2 {
index = 0
fmt.Printf("a: %+v\n", a)
jobs <- a
}
}
close(jobs)
}
func main() {
var wg sync.WaitGroup
wg.Add(1)
jobs := make(chan []int, 2)
go producer(jobs, &wg)
for job := range jobs {
fmt.Printf("job: %+v\n", job)
}
wg.Wait()
}
预期输出:
a: [0 1]
a: [2 3]
job: [0 1]
job: [2 3]
实际输出:
a: [0 1]
a: [2 3]
job: [2 3]
job: [2 3]
白猪掌柜的
汪汪一只猫
相关分类