duanliang1019 2018-09-18 10:50
浏览 43
已采纳

通过Go通道流数据

I'm trying to build a function that I pass a channel to and when run in a go routine it will constantly post updates (in this instance, values of sin) to a channel. When data is sent the the channel, I then want to send it over a web socket.

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))
}

It seems to get stuck at value <- main.Sin(div) stopping the rest of main() from running. How do i get sineWave to run indefinitely in the background and to print its output in another function as they arrive?

  • 写回答

1条回答 默认 最新

  • dongpan8439 2018-09-18 11:17
    关注

    There is several mistakes in this code,

    • the value chan is never drained, so any write will block
    • the value chan is never closed, so any drain will be infinite

    A channel must always be drained, a channel must be closed at some point.

    Also, please post reproducible examples, otherwise it is difficult to diagnose the issue.

    This is a slightly modified but working version of the OP code.

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么