猿问

通过 go 通道流式传输数据

我正在尝试构建一个将通道传递给的函数,当在 go 例程中运行时,它会不断将更新(在本例中为 sin 的值)发布到通道。当数据通过通道发送时,我想通过网络套接字发送它。


func sineWave(value chan float64) {

    var div float64

    sinMult := 6.2839

    i := 0

    log.Println("started")


    for {

        div = (float64(i+1) / sinMult)

        log.Println(math.Sin(div))

        time.Sleep(100 * time.Millisecond)

        value <- math.Sin(div)

        // log.Println()


        i++

        if i == 45 {

            i = 0

        }

    }

    // log.Println(math.Sin(div * math.Pi))

}

它似乎卡在value <- main.Sin(div)停止运行 main() 的其余部分。我如何让 sineWave 在后台无限期运行并在它们到达时在另一个函数中打印它的输出?


精慕HU
浏览 87回答 1
1回答

眼眸繁星

这段代码有几个错误,值 chan 永远不会耗尽,所以任何写入都会阻塞价值通道永远不会关闭,所以任何流失都是无限的通道必须始终排空,通道必须在某个时刻关闭。另外,请发布可重现的示例,否则很难诊断问题。这是 OP 代码的略微修改但有效的版本。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math"&nbsp; &nbsp; "time")func sineWave(value chan float64) {&nbsp; &nbsp; defer close(value) // A channel must always be closed by the writer.&nbsp; &nbsp; var div float64&nbsp; &nbsp; sinMult := 6.2839&nbsp; &nbsp; i := 0&nbsp; &nbsp; fmt.Println("started")&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; div = (float64(i+1) / sinMult)&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(100 * time.Millisecond)&nbsp; &nbsp; &nbsp; &nbsp; value <- math.Sin(div)&nbsp; &nbsp; &nbsp; &nbsp; i++&nbsp; &nbsp; &nbsp; &nbsp; if i == 4 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // i = 0 // commented in order to quit the loop, thus close the channel, thus end the main for loop&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; value := make(chan float64)&nbsp; &nbsp; go sineWave(value) // start writing the values in a different routine&nbsp; &nbsp; // drain the channel, it will end the loop whe nthe channel is closed&nbsp; &nbsp; for v := range value {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(v)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答