我正在尝试编写一个程序,其中生成通道并通过管道传递信息。我有一个频道从上游频道接收数据,然后简单地将其向下传递到下一个频道,持续一定次数。我的问题是,该函数似乎正在将输入发送到下一个通道,但在接收方,仅接收和打印其他所有消息。我不太确定发生了什么。
代码如下:
//Function that receives an array of [3]Point3D, and then sends it to the outputStream n times
func takeN(inputStream <-chan [3]Point3D, closeInputStream chan<- bool, n int) <-chan [3]Point3D {
outputStream := make(chan [3]Point3D)
go func() {
//Receives points n times and resends them
for i := 0; i < n; i++ {
in := <-inputStream
outputStream <- in
fmt.Println("out from takeN: ", in)
}
//Terminate initial stage of the pipeline once done
closeInputStream <- true
//Close the output stream to let downstream functions know there won't be any more outputs
close(outputStream)
return
}()
return outputStream
}
func main() {
// Channel used to send the stop signal for the upstream portion of the pipeline
stopChan := make(chan bool)
//Channels that generate inputs for takeNChan
singlePointChan := RandomGenerator(stopChan, pointCloud)
triplePointChan := TripletGenerator(singlePointChan)
takeNChan := takeN(triplePointChan, stopChan, 10)
//Here is the problem: this print statement is only executed 5 times, when it should be executed 10 times. Even with a buffered channel, it only prints 5 times
for range takeNChan {
received := <-takeNChan
fmt.Println("main takeNchan: ", received)
}
time.Sleep(time.Second * 5)
}
在main函数中,收到的消息只打印了5次(应该是10次)。
当我运行代码时,我得到以下输出:
out from takeN: [{-2.74 -11.45 2.52} {-7.26 -11.21 2.72} {9.96 -1.3 -0.83}]
out from takeN: [{5.46 2.68 -0.72} {1.15 -11.61 3.18} {0.22 -3.58 -0.29}]
main takeNchan: [{5.46 2.68 -0.72} {1.15 -11.61 3.18} {0.22 -3.58 -0.29}]
out from takeN: [{-1.98 -4.16 -0.89} {3.71 -2.35 -0.85} {0.51 4.47 -0.75}]
out from takeN: [{0.4 -3.34 0} {63.21 -7.23 2.88} {-1.43 -11.51 3.41}]
main takeNchan: [{0.4 -3.34 0} {63.21 -7.23 2.88} {-1.43 -11.51 3.41}]
out from takeN: [{-3.61 6.79 0.01} {1.14 5.29 -0.15} {12.73 9.59 2.49}]
out from takeN: [{-2.07 -4.47 -0.59} {1.95 2.27 -0.79} {26.1 13.95 -0.27}]
main takeNchan: [{-2.07 -4.47 -0.59} {1.95 2.27 -0.79} {26.1 13.95 -0.27}]
out from takeN: [{5.39 -0.66 -0.8} {29.96 11.26 0.02} {8.17 9.86 1.76}]
out from takeN: [{2.28 2.21 -0.77} {6.91 -7.32 -0.55} {4.77 -0.25 -0.79}]
main takeNchan: [{2.28 2.21 -0.77} {6.91 -7.32 -0.55} {4.77 -0.25 -0.79}]
out from takeN: [{-0.99 -3.73 -0.46} {-4.26 7.85 -0.65} {1.33 -11.6 3.57}]
out from takeN: [{5.31 -11.23 -0.11} {2.01 2.47 -0.78} {5.24 -11.25 -0.45}]
main takeNchan: [{5.31 -11.23 -0.11} {2.01 2.47 -0.78} {5.24 -11.25 -0.45}]
如您所见,只有每隔一个输出在 main() 函数中被接收并打印 5 次,每隔一个消息从 takeN 函数发送。
根据我的理解,打印“out from takeN”应该只在之前的行上发送一条消息后执行,因为 goroutine 中的代码是顺序的,对吧?我认为在接收者准备好之前不应该将消息发送出频道,那么为什么消息被发送出去但似乎没有收到?
最后由于time.sleep,程序挂了一点,所以我认为不是因为主程序提前退出了。 我也尝试过缓冲输出通道,但这也没有用。
您从频道接收了两次 - 并丢弃了第一个值。改变这个:
for range takeNChan {
received := <-takeNChan
fmt.Println("main takeNchan: ", received)
}
至:
for received := range takeNChan {
fmt.Println("main takeNchan: ", received)
}