通过Go通道流数据

时间:2018-09-18 10:50:57

标签: go

我正在尝试构建将通道传递给的函数,并且在执行go例程时,它将不断向通道发布更新(在这种情况下,即sin的值)。通道发送数据后,我想通过Web套接字发送数据。

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在后台无限期运行并在到达时在其他函数中打印其输出?

1 个答案:

答案 0 :(得分:3)

此代码中有几个错误,

  • 值chan永远不会耗尽,因此任何写操作都会阻塞
  • 值chan永远不会关闭,所以任何消耗都是无限的

通道必须始终排空,通道必须在某个时刻关闭。

另外,请发布可复制的示例,否则很难诊断出问题。

这是OP代码的稍作修改但可以使用的版本。

package main

import (
    "fmt"
    "math"
    "time"
)

func sineWave(value chan float64) {
    defer close(value) // A channel must always be closed by the writer.
    var div float64
    sinMult := 6.2839
    i := 0
    fmt.Println("started")

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

        time.Sleep(100 * time.Millisecond)
        value <- math.Sin(div)

        i++
        if i == 4 {
            // i = 0 // commented in order to quit the loop, thus close the channel, thus end the main for loop
            break
        }
    }

}

func main() {
    value := make(chan float64)
    go sineWave(value) // start writing the values in a different routine
    // drain the channel, it will end the loop whe nthe channel is closed
    for v := range value {
        fmt.Println(v)
    }
}