我正在尝试实现一个函数,该函数使用通道向另一个发送不确定数量的变量(float64 类型)。
第二个函数将接收并按照接收顺序创建一个切片。
这是为我已经开发的系统添加更多功能的练习。这就是为什么以这种方式说明代码的原因。
当缓冲区为1时,程序进入死锁。如果我将它增加到 7(= 切片长度),程序运行错误并且不会停止。
我理解缓冲区应该等于0或不大于1,以确保不丢失数据和顺序。
https://play.golang.org/p/rnLH51GinsG
我希望你能帮助我。
package main
import (
"fmt"
"sync"
)
var waitgroup sync.WaitGroup
/* This function simulates another that sends an
undetermined amount of float64.*/
func sendFloat64() <-chan float64 {
channel := make(chan float64, 7) // Buffer = 1 to ensure receipt of the first data before sending the second
defer close(channel)
originalSlice := []float64{90, 180, 270, 300, 330, 358, 359} // It represents an undetermined number of values.
for _, v := range originalSlice {
channel <- v // one value at a time to keep order
fmt.Println("SendFloat64: send data to channel", v)
}
return channel
}
/* This function receives the values and then it will be
incorporated in a slice respecting the order in which they were sent.*/
func RecreateSlice() <-chan []float64 {
waitgroup.Add(1)
defer waitgroup.Done()
channelOut := make(chan []float64)
defer close(channelOut)
var slice []float64
for {
dataRecived, ok := <-sendFloat64()
if !ok {
break
}
fmt.Println("RecreateSlice: Data received from channel", dataRecived)
slice = append(slice, dataRecived)
}
channelOut <- slice
return channelOut
}
慕沐林林
海绵宝宝撒
随时随地看视频慕课网APP
相关分类